猿问

我需要帮助将算法转换为 java

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

}

我知道我的 for 循环是错误的,但我不知道如何使它正确。希望有人可以帮助我。提前致谢


    for (int k = 1; k < num; k++)

    {

        int j = i + j;

        int i = j - 1;

    }


牧羊人nacy
浏览 120回答 3
3回答

潇潇雨雨

如果您在 java 中的循环内声明变量,则在迭代结束时它们就消失了。public int fibIterative(int num) {&nbsp; &nbsp; int i = 1;&nbsp; &nbsp; int j = 0;&nbsp; &nbsp; for (int k = num; k <= num; k++) {&nbsp; &nbsp; &nbsp; &nbsp; j = i + j;&nbsp; &nbsp; &nbsp; &nbsp; i = j - 1;&nbsp; &nbsp; }&nbsp; &nbsp; return j;}

喵喵时光机

转换后的代码将是:public int fibInteractive(int num) {&nbsp; &nbsp; int i = 1;&nbsp; &nbsp; int j = 0;&nbsp; &nbsp; for (int k = 1; k <= num; k++) {&nbsp; &nbsp; &nbsp; &nbsp; j = i + j;&nbsp; &nbsp; &nbsp; &nbsp; i = j - 1;&nbsp; &nbsp; }&nbsp; &nbsp; return j;}但是,我认为这段代码不会按照您的预期工作。由于i在每次迭代中重置的方式,将4 作为参数传递仍然产生 1 作为返回值:// Iteration #1j = 1 + 0i = 1 - 1// j's value at this point is 1. i's value is 0.// Iteration #2j = 0 + 1i = 1 - 1// j's value at this point is 1. i's value is 0.

慕妹3146593

public class fibIterative {&nbsp; public int AfibIterative (int num)&nbsp; {&nbsp; &nbsp; int i = 1;&nbsp; &nbsp; int j = 0;&nbsp; &nbsp; for (int k = 1; k < num; k++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;j = i + j;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i = j - 1;&nbsp; &nbsp; }&nbsp; &nbsp; return j;&nbsp; &nbsp;&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答