【发布时间】:2012-10-22 08:23:29
【问题描述】:
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
【问题讨论】:
-
递归方法中没有基本情况!
-
如果你需要它在十次后停止,你需要一个变量来表示它被递归的次数。
-
您需要将幂作为参数传递,例如
power(baseName, n);,每次递归时将幂减一。
标签: java methods recursion exponent