Java Math pow()

pow() 方法返回第一个参数的第二个参数次幂的结果。

示例

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

// computes 5 raised to the power 3 System.out.println(Math.pow(5, 3));
} } // Output: 125.0

Math.pow() 的语法

即,pow(a, b) = ab

pow() 方法的语法是

Math.pow(double num1, double num2)

这里,pow() 是一个静态方法。因此,我们使用类名 Math 来访问该方法。


pow() 参数

pow() 方法接受两个参数。

  • num1 - 基数参数
  • num2 - 指数参数

pow() 的返回值

  • 返回 num1num2 的结果
  • 如果 num2 为零,则返回 1.0
  • 如果 num1 为零,则返回 0.0

注意pow() 方法有多种特殊情况。要了解所有特殊情况,请访问 Java Math.pow() 特殊情况(官方 Java 文档)


示例:Java Math pow()

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

    // create a double variable
    double num1 = 5.0;
    double num2 = 3.0;

    // Math.pow() with positive numbers
System.out.println(Math.pow(num1, num2)); // 125.0
// Math.pow() with zero double zero = 0.0;
System.out.println(Math.pow(num1, zero)); // 0.0 System.out.println(Math.pow(zero, num2)); // 1.0
// Math.pow() with infinity double infinity = Double.POSITIVE_INFINITY;
System.out.println(Math.pow(num1, infinity)); // Infinity System.out.println(Math.pow(infinity, num2)); // Infinity
// Math.pow() with negative numbers
System.out.println(Math.pow(-num1, -num2)); // 0.008
} }

在上面的示例中,我们使用了 Math.pow()正数负数无穷大进行了运算。

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

注意:当我们将一个 整数值 传递给 pow() 方法时,它会自动将 int 值转换为 double 值

int a = 2;
int b = 5;

Math.pow(a, b);   // returns 32.0

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战