當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java StrictMath sqrt()用法及代碼示例


java.lang.StrictMath.sqrt()是Java中StrictMath類的內置方法,用於獲取指定雙精度值的精確四舍五入的正平方根。

用法:

public static double sqrt(double num)

參數:該函數接受雙精度類型的單個參數num,該參數的平方根將由該函數返回。


返回值:此方法返回num的正平方根。它也引起了特殊情況:

  • 如果參數為NaN或小於零,則函數返回NaN
  • 當參數為正無限大時,該函數返回正無限大。
  • 如果參數為零,則該函數返回零且符號與參數相同
  • 結果是最接近參數值的數學平方根的double值。

例子:

Input: num = 25
Output: 5.0

Input: -729
Output: NaN

以下程序說明了java.lang.StrictMath.sqrt()方法的使用:

示例1:

// Java Program to illustrate 
// java.lang.StrictMath.sqrt() function 
import java.lang.*; 
  
public class Geeks { 
  
    public static void main(String[] args) 
    { 
  
        double num1 = 289, num2 = -729; 
        double num3 = 0.0, num4 = 547.87; 
  
        // It returns the positive square root 
        double sqrt_Value = StrictMath.sqrt(num1); 
        System.out.println("square root = " + sqrt_Value); 
  
        sqrt_Value = StrictMath.sqrt(num2); 
        System.out.println("square root = " + sqrt_Value); 
  
        sqrt_Value = StrictMath.sqrt(num3); 
        System.out.println("square root = " + sqrt_Value); 
  
        sqrt_Value = StrictMath.sqrt(num4); 
        System.out.println("square root = " + sqrt_Value); 
    } 
}
輸出:
square root = 17.0
square root = NaN
square root = 0.0
square root = 23.406622994357814

示例2:

// Java Program to illustrate 
// java.lang.StrictMath.sqrt() function 
import java.lang.*; 
  
public class Geeks { 
  
    public static void main(String[] args) 
    { 
  
        double num1 = 1160, num2 = -97; 
        double num3 = -0.0, num4 = 144; 
        double num5 = -72.18; 
  
        // It returns the positive square root 
        double sqrt_Value = StrictMath.sqrt(num1); 
        System.out.println("square root = " + sqrt_Value); 
  
        sqrt_Value = StrictMath.sqrt(num2); 
        System.out.println("square root = " + sqrt_Value); 
  
        sqrt_Value = StrictMath.sqrt(num3); 
        System.out.println("square root = " + sqrt_Value); 
  
        sqrt_Value = StrictMath.sqrt(num4); 
        System.out.println("square root = " + sqrt_Value); 
  
        sqrt_Value = StrictMath.sqrt(num5); 
        System.out.println("square root = " + sqrt_Value); 
    } 
}
輸出:
square root = 34.058772731852805
square root = NaN
square root = -0.0
square root = 12.0
square root = NaN


相關用法


注:本文由純淨天空篩選整理自ankita_chowrasia大神的英文原創作品 StrictMath sqrt() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。