Java - Math copySign(float) 方法



描述

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

宣告

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

public static float copySign(float magnitude, float sign)

引數

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

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

返回值

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

異常

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

以下示例演示了 Math copySign() 方法的用法。

package com.tutorialspoint;

public class MathDemo {

   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("Math.copySign(" + x + "," + y + ")=" + Math.copySign(x, y));
   }
}

輸出

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

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

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

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

package com.tutorialspoint;

public class MathDemo {

   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("Math.copySign(" + y + "," + x + ")=" + Math.copySign(y, x));
   }
}

輸出

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

Math.copySign(-0.4873, 125.9)=0.4873

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

以下示例演示了對零值的 Math copySign() 方法的用法。

package com.tutorialspoint;

public class MathDemo {

   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("Math.copySign(" + x + "," + y + ")=" + Math.copySign(x, y));
   }
}

輸出

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

Math.copySign(0.0,-0.4873)=-0.0
java_lang_math.htm
廣告