即pow(a, b) = a b
pow()
方法的语法为:
Math.pow(double num1, double num2)
在这里, pow()
是静态方法。因此,我们使用类名Math
来访问该方法。
pow()参数
pow()
方法采用两个参数。
- num1-基本参数
- num2-指数参数
pow()返回值
- 返回num1 num2的结果
- 如果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
推荐的教程
- Java Math.cbrt()
- Java Math.sqrt()