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