public static int exponent(int baseNum) {
int temp = baseNum *= baseNum;
return temp * exponent(baseNum);
}
现在,如果我调试上面的方法,它会 n * n 变成无穷大,所以它仍然有效,但我需要这个递归方法在 10 次后停止,因为我的导师要求我们找到给定 10 次方的指数。
该方法必须只有一个参数,下面是一些调用指数的例子:
System.out.println ("The power of 10 in " + n + " is " +
exponent(n));
所以输出应该是:
The power of 10 in 2 is 1024
或
The power of 10 in 5 is 9765625
最佳答案
做类似的事情
public static int exp(int pow, int num) {
if (pow < 1)
return 1;
else
return num * exp(pow-1, num) ;
}
public static void main (String [] args) {
System.out.println (exp (10, 5));
}
并且不要忘记告知何时停止递归并从堆栈中弹出值的基本情况(即条件)。
关于java - 递归指数法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13182314/