一个非常新的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);
        }
      }

最佳答案

由于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加1:

  .---。 .---。 .---。 .---。 .---。
  | 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加1:

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


然后返回顶部以比较现在的c < numToPrint
false,因此程序结束。

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

10-08 00:09