Java教程

Java Math pow()

Java Math pow()

在本教程中,我们将通过示例了解 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.

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()/strong> 和 无穷大。
这里, Double.POSITIVE_INFINITY用于在程序中实现正无穷大。
注意: 当我们将整数值传递给 pow() 方法时,它会自动将 int 值转换为 double 值。
int a = 2;
int b = 5;
Math.pow(a, b);   // returns 32.0

推荐教程

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