递归指数法 [英] Recursive Exponent Method
问题描述
public static int exponent(int baseNum) {
int temp = baseNum *= baseNum;
return temp * exponent(baseNum);
}
现在,如果我调试它,上面的方法会将n * n转换为无穷大,所以它仍然可以工作,但我需要这个递归方法在10次后停止,因为我的教练要求我们找到给定10的幂的指数。
Right now the method above does n * n into infinity if I debug it, so it still works but I need this recursive method to stop after 10 times because my instructor requires us to find the exponent given a power of 10.
该方法必须只有一个参数,这里是调用指数的一些例子:
The method must have only one parameter, here's some examples of calling exponent:
System.out.println ("The power of 10 in " + n + " is " +
exponent(n));
因此输出应为:
The power of 10 in 2 is 1024
OR
The power of 10 in 5 is 9765625
推荐答案
创建一个辅助方法来进行递归。它应该有两个参数:base和exponent。为指数调用值10,并使用(exponent-1)递归。基本情况是 exponent == 0
,在这种情况下它应该返回1.(你也可以使用 exponent == 1
作为基本情况,在这种情况下它应该返回基数。)
Create an auxiliary method to do the recursion. It should have two arguments: the base and the exponent. Call it with a value of 10 for the exponent and have it recurse with (exponent-1). The base case is exponent == 0
, in which case it should return 1. (You can also use exponent == 1
as a base case, in which case it should return the base.)
这篇关于递归指数法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!