求斐波纳契数列中所有偶数项的总和

kac*_*ous 3 java fibonacci

我无法确定以下代码为什么不产生预期的输出.相反,结果= 272似乎不正确.

/*
 *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, ...
 *Find the sum of all the even-valued terms in the sequence which do not exceed four million.
 */

public class Fibonacci 
{
    public static void main (String[] args)
    {
        int result = 0;
        for(int i=2;i<=33;i++)
        {
            System.out.println("i:" + fib(i)); 
            if(i % 2 == 0) //if i is even 
            {
                result += i;
                System.out.println("result:" + result); 
            }
        }
    }   
    public static long fib(int n)
    {
        if (n <= 1)
            return n;
        else
            return fib(n-1) + fib(n-2);
    }
}    
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 5

该行result += i;不会添加斐波纳契result.

您应该能够弄清楚如何使其添加斐波纳契result.

提示:考虑创建一个存储您尝试使用的数字的变量.

  • 另外,行if(i%2 == 0)`不测试*Fibonacci*数是否是偶数. (2认同)