java - 找出斐波那契数列中所有偶数项的总和

标签 java fibonacci

我无法理解为什么以下代码没有产生预期的输出。相反, result = 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);
    }
}    

最佳答案

result += i; 没有将 Fibonacci 数添加到 result

您应该能够弄清楚如何让它向 result 添加一个 Fibonacci 数。

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

关于java - 找出斐波那契数列中所有偶数项的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4180407/

相关文章:

c++ - 如何将递归转换为迭代解决方案

java - 大斐波那契与 GCD

java - 如何使用 Java 的 StringTokenizer 访问特定的标记?

java - 如何将 WebStart JNLP 与 JRE 捆绑在一起

java - 如何在eclipse中运行这个spring rest maven项目

objective-c - 将 NSDecimalNumber 与 Binet 公式结合使用斐波那契数列

python - 具有可变繁殖力的斐波那契凡人兔子

java - ActionListener 无法识别来自主类的变量

java - 从两个表中获取相似的列名和计数

c++ - 为什么 (int)55 == 54 在 C++ 中?