当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。