Java - Math sqrt(double x) 方法



描述

Java Math sqrt(double a) 方法返回雙精度值的正確舍入的正平方根。特殊情況 -

  • 如果引數是 NaN 或小於零,則結果為 NaN。

  • 如果引數是正無窮大,則結果是正無窮大。

  • 如果引數是正零或負零,則結果與引數相同。

否則,結果是最接近引數值的真實數學平方根的雙精度值。

宣告

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

public static double sqrt(double a)

引數

a − 一個值。

返回值

此方法返回 a 的正平方根。如果引數是 NaN 或小於零,則結果為 NaN。

異常

示例:獲取正雙精度值的平方根

以下示例演示瞭如何使用 Math sqrt() 方法獲取正雙精度值的平方根。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get a double number
      double x = 1654.9874;

      // find the square root for this double number
      System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
   }
}

輸出

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

Math.sqrt(1654.9874)=40.68153635250272

示例:獲取負雙精度值的平方根

以下示例演示瞭如何使用 Math sqrt() 方法獲取負雙精度值的平方根。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get a double number
      double x = -9765.134;

      // find the square root for this double number
      System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
   }
}

輸出

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

Math.sqrt(-9765.134)=NaN

示例:獲取零雙精度值的平方根

以下示例演示瞭如何使用 Math sqrt() 方法獲取零雙精度值的平方根。

package com.tutorialspoint;
public class MathDemo {
   public static void main(String[] args) {

      // get double number
      double x = 0.0;	  

      // find the square root for this double number
      System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
   }
}

輸出

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

Math.sqrt(0.0)=0.0
java_lang_math.htm
廣告