甚至斐波那契数字都是C,难题

时间:2013-03-16 23:27:51

标签: c

问题:

  

Fibonacci序列中的每个新术语都是通过添加前两个术语生成的。从1和2开始,前10个术语将是:

     

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

     

通过考虑Fibonacci序列中的值不超过四百万的项,找到偶数项的总和。

我已经查找了另一种方法来做到这一点,但我很困惑为什么我的方法不起作用。我已经包含了代码以及我下面的书面算法流程。无论我选择的值k的哪个迭代范围(4000000或10),我总会收到相同的答案:4200784。感谢您的帮助。

#include <stdio.h>

int main()
{
long int sum;
sum = 0;
long int i;
i = 1;
long int j;
j = 2;
long int k;

while(k<4000000)
{   
    k = i + j;
    if(k%2==0)
        sum +=k;
    i = j;
    j = k;

}
printf("%d",sum);
return 0;
}

//Step 0//For the initial conditions [i][j]=[1][2]
//Step 1//Find the value of i + j.
//Step 2//Find out if the solution is even by dividing by modulus 2.
//Step 3//If even, add the solution to the sum.
//Step 4//Replace the value of i with j, and replace the value of j with the new sum.
//Repeat Steps 1-4 while i + j < 4,000,000
//1, 2, 3, 5, 8, 13, 21, 34

2 个答案:

答案 0 :(得分:3)

我相信你在寻找

sum += k;

k+=sum;

您还应修复此问题并将其放入while循环中

k = i + j;

注意:您还应该将sum初始化为0

答案 1 :(得分:1)

您永远不会初始化'k'变量。在第一次'while'测试中,你有一个未定义的'k'值,所以所有的赌注都关闭了。