Fibonacci - 为什么这给我错误的计算?

Fibonacci - Why is this giving me the incorrect calculation?

问题是...

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

我已经编写了一个应该执行此操作的代码,粘贴在下面:

public class Main {
    public static void main(String[] args) {
        // Setting up the variables. sumF3 will be printed at the end.
        int sumF1 = 1;
        int sumF2 = 2;
        int sumF3 = 0;
        // If loops to cancel out the odd numbers, but let them be added to sumF2 etc anyway.
        while(4000000 > sumF1) {
            if (sumF1 % 2 == 0) {
                sumF3 += sumF1;
            }
            if (sumF2 % 2 == 0) {
                sumF3 += sumF2;
            }
            // Normal fibonacci sequence.
            sumF1 += sumF1 + sumF2;
            sumF2 += sumF1 + sumF2;
        }
        System.out.println(sumF3);
    }
}

我首先用两个 if 循环过滤掉奇数,然后将其添加到 sumF3。它将继续添加到 sumF3 中,直到它达到 400 万以下。当 while 循环停止时,它应该打印出“4613732”,但它打印出不同的东西 (4194302)。感觉这里逻辑有问题

其实你只是犯了一个小错误。行数

sumF1 += sumF1 + sumF2;
sumF2 += sumF1 + sumF2;

应该是

sumF1 = sumF1 + sumF2;
sumF2 = sumF1 + sumF2;

注意 = 而不是 +=

你的斐波那契数列表达式不正确。您正在执行以下操作:

// Normal fibonacci sequence.
        sumF1 += sumF1 + sumF2;
        sumF2 += sumF1 + sumF2;

本质上是这样做的:

sumF1 = sumF1+sumF1+sumF2, sumF2 = sumF2+sumF1+sumF2.

如果将表达式更改为以下内容,您应该会得到正确答案:

// Normal fibonacci sequence.
        sumF1 += sumF2;
        sumF2 += sumF1;

+= 运算符将表达式的值与变量的值相加,并将结果赋给变量。您正在混合中添加一个额外的变量,这会影响您的结果。