可以使用递归来计算数字的幂。这里的数字是x,并乘幂n。
演示此过程的程序如下:
示例public class Demo {
static double pow(double x, int n) {
if (n != 0)
return (x * pow(x, n - 1));
else
return 1;
}
public static void main(String[] args) {
System.out.println("7 to the power 3 is " + pow(7, 3));
System.out.println("4 to the power 1 is " + pow(4, 1));
System.out.println("9 to the power 0 is " + pow(9, 0));
}
}
输出结果7 to the power 3 is 343.0
4 to the power 1 is 4.0
9 to the power 0 is 1.0
现在让我们了解上面的程序。
该方法pow()计算x的幂n。如果n不为0,则递归调用自身并返回x * pow(x,n-1)。如果n为0,则返回1。演示此代码段如下:static double pow(double x, int n) {
if (n != 0)
return (x * pow(x, n - 1));
else
return 1;
}
在中main(),pow()使用不同的值调用该方法。演示此代码段如下:public static void main(String[] args) {
System.out.println("7 to the power 3 is " + pow(7, 3));
System.out.println("4 to the power 1 is " + pow(4, 1));
System.out.println("9 to the power 0 is " + pow(9, 0));
}