使用 Java 中的递归将 x 提升到 n 次方
可以使用递归计算一个数的幂。这里,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));
}
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP