【发布时间】:2020-12-18 01:49:12
【问题描述】:
我正在使用递归方法来计算,并且为了跟踪结果,我正在使用全局静态变量来存储结果。虽然,我的代码是不正确的,因为在考虑基本情况时。根据我的代码,power(2,3) 应该返回 4。如果我使用空运行方法进行检查。但实际上,ans 变量的值在整个执行过程中只改变一次。我的问题是,为什么 ans 的值没有得到更新,并且对于任何 power n 值和 base 为 2。我的答案总是作为基值本身返回。谁能调试我的代码并帮助我理解递归方法调用中全局静态变量的行为
public class Solution {
static int ans=1;
public static int power(int x, int n) {
/* Your class should be named Solution
* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
if(n==0)
return 1;
if(n==1)
return x;
else
ans=ans*power(x,n-1);
return ans;
}
}
【问题讨论】:
-
else 语句
ans = ...中的变量ans在评估最后一个power(x,n-1)之前不会更新。第一个评估将是x,因为它会在n == 1的情况下返回。之后,所有待处理的ans = ans * power(...)评估将计算ans = 1 * x。 -
你应该为 ans 使用一个局部变量。
标签: java recursion static static-variables