Java - StrictMath copySign(float) 方法



描述

Java StrictMath copySign(float magnitude, float sign) 方法返回第一個浮點數引數,其符號與第二個浮點數引數的符號相同。

宣告

以下是java.lang.StrictMath.copySign() 方法的宣告

public static float copySign(float magnitude, float sign)

引數

  • magnitude − 提供結果大小的引數

  • sign − 提供結果符號的引數

返回值

此方法返回一個值,其大小為 magnitude,符號為 sign。

異常

獲取第一個浮點數引數,複製第二個正浮點數引數的符號示例

以下示例顯示了 StrictMath copySign() 方法的用法。

package com.tutorialspoint;

public class StrictMathDemo {

   public static void main(String[] args) {

      // get two float numbers
      float x = 125.9f;
      float y = -0.4873f;
   
      // print a float with the magnitude of x and the sign of y
      System.out.println("StrictMath.copySign(" + x + "," + y + ")=" + StrictMath.copySign(x, y));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

StrictMath.copySign(125.9, -0.4873)=-125.9

獲取第一個浮點數引數,複製第二個負浮點數引數的符號示例

以下示例顯示了使用引數交換的 StrictMath copySign() 方法的另一種用法。

package com.tutorialspoint;

public class StrictMathDemo {

   public static void main(String[] args) {

      // get two float numbers
      float x = 125.9f;
      float y = -0.4873f;
   
      // print a float with the magnitude of y and the sign of x
      System.out.println("StrictMath.copySign(" + y + "," + x + ")=" + StrictMath.copySign(y, x));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

StrictMath.copySign(-0.4873, 125.9)=0.4873

獲取零值並複製第二個浮點數引數的符號示例

以下示例顯示了對零值使用 StrictMath copySign() 方法的用法。

package com.tutorialspoint;

public class StrictMathDemo {

   public static void main(String[] args) {

      // get two float numbers
      float x = 0f;
      float y = -0.4873f;
   
      // print a float with the magnitude of x and the sign of y
      System.out.println("StrictMath.copySign(" + x + "," + y + ")=" + StrictMath.copySign(x, y));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

StrictMath.copySign(0.0,-0.4873)=-0.0
java_lang_strictmath.htm
廣告
© . All rights reserved.