timeout=Xs
我知道我的for循环是错误的,但是我不知道如何使它正确。 希望有人可以帮助我。预先感谢
Algorithm fibIterative(integer num)
{
set i to 1
set j to 0
for (k = 1 to num) {
set j = i + j
set i = j - i
}
return j
}
答案 0 :(得分:1)
如果您在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;
}
答案 1 :(得分:0)
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;
}
}
答案 2 :(得分:0)
转换后的代码为:
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;
}
但是,我认为这段代码不会按照您想要的方式工作。传递4作为参数仍然会产生1作为返回值,因为在每次迭代中重置i
的方式是
// 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.
答案 3 :(得分:-1)
您的完整Java程序应如下所示:
public class algorithm {
public static void main(String []args) {
int ans = fibIterative(23);
System.out.println(ans);
}
static int fibIterative(int num) {
int i = 1,j = 0,k;
for(k = 1;k <= num; k++) {
j = i + j;
i = j - i;
}
return j;
}
}