需要帮助-基本的Java代码。(Fibonacci系列)

bob9123

一个非常新的Java程序员,我正在尝试解决这个斐波那契问题。(省略导入/类定义

    Scanner sc = new Scanner(System.in);
    System.out.print("Put in how many you want to input");
    numToPrint = sc.nextInt();
    sc.close();

    int current = 1;
    int last = 0;
    System.out.println(last);
    System.out.println(current);

    // This is the section I don't really understand.
    int lastlast;
    for (int c =2; c < numToPrint; c++){
        lastlast = last; //How does last variable change from 0 as assigned from above?
        last = current; // How does current variable change from 1? 
        current = lastlast + last;
        System.out.println(current);
        }
      }
Brian Tompsett - 汤莱恩

由于OP是一个非常新的Java程序员,因此我认为像在初学者课堂中那样做一个小型教程可能会有所帮助。

对方的回应是正确的,但每个人都必须从某个地方开始。

好的。您不了解的部分有几个整数变量,它们是计算机内存中存储位置的名称。我将它们绘制出来以显示它们存储的内容(当前它们为空):

  - - - - - 
  | | | | | | | | | | 
  ' 
---'' --- '' --- '' --- ''--- ' numToPrint当前最后一个lastlast c

现在,在Java中,程序启动时,新变量将初始化为零。(顺便说一句,并非所有语言都适用)。

我将值设置为它们在阅读(例如)4后位于注释处的值:

//This is the section I don't really understand

  - - - - - 
  | 4 | | 1 | | 0 | | 0 | | 0 | 
  ' 
---'' --- '' --- '' --- ''--- ' numToPrint当前最后一个lastlast c

现在,继续进行几行,我们开始循环:

for (int c =2; c < numToPrint; c++) {

我们可以看到c < numToPrinttrue这样所以我们继续:

  - - - - - 
  | 4 | | 1 | | 0 | | 0 | | 2 | 
  ' 
---'' --- '' --- '' --- ''--- ' numToPrint当前最后一个lastlast c

接下来的两行将被执行:

lastlast = last; last = current;

  - - - - - 
  | 4 | | 1 | | 1 | | 0 | | 2 | 
  ' 
---'' --- '' --- '' --- ''--- ' numToPrint当前最后一个lastlast c

然后,下一行是:

current = lastlast + last;

  - - - - - 
  | 4 | | 1 | | 1 | | 0 | | 2 | 
  ' 
---'' --- '' --- '' --- ''--- ' numToPrint当前最后一个lastlast c

然后: System.out.println(current);

输出“ 1”

在循环的底部,我们加c一:

  - - - - - 
  | 4 | | 1 | | 1 | | 0 | | 3 | 
  ' 
---'' --- '' --- '' --- ''--- ' numToPrint当前最后一个lastlast c

然后返回顶部以比较c < numToPrint仍然是true,因此我们继续:

接下来的两行将被执行:

lastlast = last; last = current;

  - - - - - 
  | 4 | | 1 | | 1 | | 1 | | 3 | 
  ' 
---'' --- '' --- '' --- ''--- ' numToPrint当前最后一个lastlast c

然后,下一行是:

current = lastlast + last;

  - - - - - 
  | 4 | | 2 | | 1 | | 1 | | 3 | 
  ' 
---'' --- '' --- '' --- ''--- ' numToPrint当前最后一个lastlast c

然后: System.out.println(current);

输出“ 2”

在循环的底部,我们加c一:

  - - - - - 
  | 4 | | 2 | | 1 | | 1 | | 4 | 
  ' 
---'' --- '' --- '' --- ''--- ' numToPrint当前最后一个lastlast c

然后回到顶部比较c < numToPrint现在是哪个false,因此程序结束。

希望这可以帮助您更多地了解代码?(由emacs图片编辑模式和冰镇啤酒提供!)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章