Java sqrt() 方法示例

java 8object oriented programmingprogramming

java.lang.Math.sqrt(double a) 返回 double 值正确舍入后的正平方根。特殊情况 −

  • 如果参数为 NaN 或小于零,则结果为 NaN。

  • 如果参数为正无穷大,则结果为正无穷大。

  • 如果参数为正零或负零,则结果与参数相同。

以下是在 Java 中实现 Math 类的 sqrt() 方法 − 的示例

示例

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

相关文章