Java sqrt() 方法及示例
java.lang.Math.sqrt(double a) 返回双精度值的正确舍入正平方根。特殊情况 -
如果自变量为 NaN 或小于零,则结果为 NaN。
如果自变量为正无穷大,则结果为正无穷大。
如果自变量为正零或负零,则结果与自变量相同。
以下是 Java 中 Math 类 sqrt() 方法的实现示例 -
示例
import java.lang.*;
public class Demo {
public static void main(String[] args) {
// get two double numbers numbers
double x = 9;
double y = 25;
// print the square root of these doubles
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) {
// get two double numbers numbers
double x = -20.0;
double y = 0.0;
// print the square root of these doubles
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP