【发布时间】:2021-08-09 05:39:11
【问题描述】:
我想使用 while 或 for 循环将此递归方法更改为迭代方法,但遇到了麻烦。这是我要翻译的递归方法:
public static int recursiveNum (int n)
{
if(n<=2)
{
return 1;
}
else
{
return recursiveNum(n-1)+recursiveNum(n-2);
}
}
到目前为止我所做的尝试:
public static int iterativeNum (int n) {
while (i<n) {
i++;
if (n<=2) {
return 1;
}
else {
return n = (n-1) + (n-2);
}
}
return n;
}
【问题讨论】:
-
public static int iterativeNum (int n) { while (i
-
(n-1) + (n-2)对索引求和,而不是求和。您需要几个变量来跟踪以前的总和。 -
并且循环中间不应该有
return。您不能只是将递归代码转储到一个循环中,然后希望它能够正常工作。 -
如果我创建另一个变量,当 n 大于 3 时,我是否还需要更多?我应该使用数组吗?
-
为什么要使用while循环?斐波那契数列最好用函数的递归性来描述。