3 回答
TA贡献1833条经验 获得超4个赞
如果您在 java 中的循环内声明变量,则在迭代结束时它们就消失了。
public int fibIterative(int num) {
int i = 1;
int j = 0;
for (int k = num; k <= num; k++) {
j = i + j;
i = j - 1;
}
return j;
}
TA贡献1846条经验 获得超7个赞
转换后的代码将是:
public int fibInteractive(int num) {
int i = 1;
int j = 0;
for (int k = 1; k <= num; k++) {
j = i + j;
i = j - 1;
}
return j;
}
但是,我认为这段代码不会按照您的预期工作。由于i在每次迭代中重置的方式,将4 作为参数传递仍然产生 1 作为返回值:
// Iteration #1
j = 1 + 0
i = 1 - 1
// j's value at this point is 1. i's value is 0.
// Iteration #2
j = 0 + 1
i = 1 - 1
// j's value at this point is 1. i's value is 0.
TA贡献1820条经验 获得超9个赞
public class fibIterative {
public int AfibIterative (int num)
{
int i = 1;
int j = 0;
for (int k = 1; k < num; k++)
{
j = i + j;
i = j - 1;
}
return j;
}
}
添加回答
举报