跳到主要内容

Java Math sqrt() 方法

sqrt() 方法返回指定数字的平方根。

示例

class Main {
public static void main(String[] args) {

// 计算 25 的平方根
System.out.println(Math.sqrt(25));


}
}

// 输出: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) {

// 创建一个 double 变量
double value1 = Double.POSITIVE_INFINITY;
double value2 = 25.0;
double value3 = -16;
double value4 = 0.0;

// 无穷大的平方根
System.out.println(Math.sqrt(value1)); // Infinity


// 正数的平方根
System.out.println(Math.sqrt(value2)); // 5.0


// 负数的平方根
System.out.println(Math.sqrt(value3)); // NaN


// 零的平方根
System.out.println(Math.sqrt(value4)); // 0.0

}
}

在上面的示例中,我们使用了 Math.sqrt() 方法来计算无穷大、正数、负数和零的平方根。

这里,Double.POSITIVE_INFINITY 被用来在程序中实现正无穷大。

当我们向 sqrt() 方法传递一个 int 值时,它会自动将 int 值转换为 double 值。

int a = 36;

Math.sqrt(a); // 返回 6.0

推荐教程