java.lang.Math.sqrt(double a)返回double值的正确四舍五入的正平方根。特殊情况-
如果参数为NaN或小于零,则结果为NaN。
如果参数为正无穷大,则结果为正无穷大。
如果自变量为正零或负零,则结果与自变量相同。
以下是sqrt()在Java中实现Math类的方法的示例-
import java.lang.*;
public class Demo {
public static void main(String[] args) {
//得到两个双数数字
double x = 9;
double y = 25;
//打印这些双打的平方根
System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
System.out.println("Math.sqrt(" + y + ")=" + Math.sqrt(y));
}
}输出结果
Math.sqrt(9.0)=3.0 Math.sqrt(25.0)=5.0
现在让我们来看另一个示例,sqrt()以负数和其他值实现该方法-
import java.lang.*;
public class Demo {
public static void main(String[] args) {
//得到两个双精度数数字
double x = -20.0;
double y = 0.0;
//打印这些双精度数的平方根
System.out.println("Math.sqrt(" + x + ")=" + Math.sqrt(x));
System.out.println("Math.sqrt(" + y + ")=" + Math.sqrt(y));
}
}输出结果
Math.sqrt(-20.0)=NaN Math.sqrt(0.0)=0.0