Mat*_*zuk 5 java methods recursion exponent
public static int exponent(int baseNum) {
int temp = baseNum *= baseNum;
return temp * exponent(baseNum);
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我调试它,上面的方法会 n * n 变成无穷大,所以它仍然有效,但我需要这个递归方法在 10 次后停止,因为我的老师要求我们找到给定 10 次幂的指数。
该方法必须只有一个参数,以下是调用指数的一些示例:
System.out.println ("The power of 10 in " + n + " is " +
exponent(n));
Run Code Online (Sandbox Code Playgroud)
所以输出应该是:
The power of 10 in 2 is 1024
Run Code Online (Sandbox Code Playgroud)
或者
The power of 10 in 5 is 9765625
Run Code Online (Sandbox Code Playgroud)
做类似的事情
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));
}
Run Code Online (Sandbox Code Playgroud)
并且不要忘记基本情况(即条件),它告诉何时停止递归并从堆栈中弹出值。
创建一个辅助方法来执行递归。它应该有两个参数:底数和指数。使用指数值 10 来调用它,并使用 (exponent-1) 进行递归。基本情况是exponent == 0,在这种情况下它应该返回 1。(您也可以用作exponent == 1基本情况,在这种情况下它应该返回基数。)