Java教程

Java Math sqrt()

Java Math sqrt()

在本教程中,我们将通过示例了解 Java Math.sqrt() 方法。
sqrt() 方法返回指定数字的平方根。

示例

class Main {
  public static void main(String[] args) {
     // compute square root of 25 System.out.println(Math.sqrt(25)); 
  }
}
// Output: 5.0

Math.sqrt() 的语法

sqrt() 方法的语法是:
Math.sqrt(double num)
这里, sqrt() 是一个静态方法。因此,我们使用类名访问该方法, Math

sqrt() 参数

sqrt() 方法接受一个参数。
num-要计算平方根的数字

sqrt() 返回值

返回指定数字的平方根 如果参数小于 0 或 NaN,则返回 NaN
注意: 该方法总是返回正数且正确四舍五入的数。

示例: Java Math sqrt()

class Main {
  public static void main(String[] args) {
    // create a double variable
    double value1 = Double.POSITIVE_INFINITY;
    double value2 = 25.0;
    double value3 =-16;
    double value4 = 0.0;
    // square root of infinity
    System.out.println(Math.sqrt(value1)); // Infinity 
    // square root of a positive number
    System.out.println(Math.sqrt(value2)); // 5.0 
    // square root of a negative number
    System.out.println(Math.sqrt(value3)); // NaN 
    // square root of zero
    System.out.println(Math.sqrt(value4)); // 0.0 
  }
}
在上面的例子中,我们使用了 Math.sqrt() 方法来计算无穷大、正数、负数和零的平方根。
这里, Double.POSITIVE_INFINITY用于在程序中实现正无穷大。
当我们将 int 值传递给 sqrt() 方法时,它会自动将 int 值转换为 double 值。
int a = 36;
Math.sqrt(a);   // returns 6.0

推荐教程

Java Math.pow() Java Math.cbrt()
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4