循环变量的Java斐波那契

这是一个程序,它接受一个命令行变量,将其解析为一个 int,输出是等于该 cmd 行参数的斐波那契数。所以如果我输入 7,输出将是 13。因为:1 1 2 3 5 8 13 有人能解释一下 b = a;在for循环里面?既然它们都已经等于 1,为什么需要将它们设置为彼此相等呢?


    int a,b,c;

    int n = Integer.parseInt(args[0]);

    a = 1;

    b = 1;

    c = 0;

    if (n == 1 || n == 2)


        System.out.println(1);


    else 

    {

        for (int i = 3; i<=n; i++)

        {

            c = a + b;

            b = a;

            a = c;

        }

        System.out.println(c);

    }

}


慕丝7291255
浏览 108回答 2
2回答

慕沐林林

a并且最初b等于 1 ,因此在循环的第一次迭代中,该语句什么也不做。但是让我们看看在以后的迭代中会发生什么:Initial state:a = 1b = 1c = 0Iteration 1:c = 1 + 1 = 2b = a = 1a = c = 2Iteration 2:c = 1 + 2 = 3b = a = 2a = c = 3Iteration 3:c = 2 + 3 = 5b = a = 3a = c = 5本质上,a存储序列中的前一个数字,而b存储倒数第二个。由于序列的前 2 个数字是1, 1,b将在两次迭代中保持为 1,但稍后会更改。

茅侃侃

Fn = Fn-1 + Fn-2,即从a = 1and开始b = 1,您必须计算下一个斐波那契数并将 and 移动a到b右边的一个位置。public static long fibonacci(int n) {&nbsp; &nbsp; n = Math.abs(n);&nbsp; &nbsp; if (n == 0)&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; if (n < 3)&nbsp; &nbsp; &nbsp; &nbsp; return 1;&nbsp; &nbsp; long a = 1;&nbsp; &nbsp; long b = 1;&nbsp; &nbsp; long c = 0;&nbsp; &nbsp; for (int i = 3; i <= n; i++) {&nbsp; &nbsp; &nbsp; &nbsp; c = a + b;&nbsp; &nbsp; &nbsp; &nbsp; b = a;&nbsp; &nbsp; &nbsp; &nbsp; a = c;&nbsp; &nbsp; }&nbsp; &nbsp; return c;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java