简体   繁体   English

甚至C中的斐波那契数,难题

[英]Even Fibonacci numbers in C, conundrum

Problem: 问题:

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开始,前10个术语将是:

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

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. 通过考虑斐波那契数列中值不超过四百万的项,找到偶值项的总和。

I've looked up another way to do this, but I am confused as to why my method does not work. 我已经寻找了另一种方法来执行此操作,但是我对为什么我的方法不起作用感到困惑。 I've included the code as well as my written algorithmic process below it. 我将代码以及下面的书面算法过程包括在内。 No matter which span of iterations of the value k I choose (4000000 or 10), I always receive the same answer: 4200784. Thanks for the help. 无论我选择值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

I believe your looking for 我相信你在找

sum += k;

not

k+=sum;

You should also fix this and place it inside your while loop 您还应该修复此问题并将其放入while循环中

k = i + j;

Note: you should also initialize sum to 0 注意:您还应该将sum初始化为0

You never initialize your 'k' variable. 您永远不会初始化“ k”变量。 On that first 'while' test, you have an undefined value for 'k', so all bets are off. 在第一个“ while”测试中,您对“ k”的值不确定,因此所有赌注都关闭了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM