3

我无法弄清楚为什么以下代码没有产生预期的输出。相反,结果 = 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);
    }
}    
4

3 回答 3

5

该行result += i;不会将斐波那契数添加到result.

你应该能够弄清楚如何让它添加一个斐波那契result

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

于 2010-11-14T23:45:56.433 回答
1

首先,您对 Fib 有一点误解。Fib 的定义可以在这里找到:http ://en.wikipedia.org/wiki/Fibonacci_number 。

其次,(i % 2) 对所有其他数字(2、4、6 等)都为真,这将使人们认为 fib(2)、fib(4) 等也为真。

最后, result += i 添加索引。您不想添加的是 fib(i) 的结果。因此,首先您需要计算 fib(i),将其存储在变量中,并检查 THAT 是偶数还是奇数,如果是,则将变量添加到结果中。

[编辑]
最后一点:当您不想将所有数字相加时,递归执行 fib 可能非常糟糕。如果您正在处理大量数字,您甚至可能会遇到 StackOverflowException,因此尝试找出一种方法总是一个好主意,这样您就不必一遍又一遍地计算相同的数字。在这个例子中,你想对数字求和,所以不要先尝试 fib(0),然后再尝试 fib(1) 等等,你应该使用列表,检查途中的每个数字,然后将其添加到结果,如果它符合您的条件。

于 2010-11-14T23:51:06.640 回答
0

嗯,这是一个很好的起点,但它是 C,而不是 Java。不过,它可能会有所帮助:链接文本

于 2010-12-18T16:59:41.207 回答