无法让C ++ Project Euler#2完全正确

时间:2016-11-28 20:43:19

标签: c++

  

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

     

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

     

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

我也提到过这个question,但它对我的案例没什么帮助。

当我将序列限制为10时,我得到了偶数值项的总和。这是我的代码:

#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 1, z, sumeven = 0;

for (int stop=1; stop <= 5; stop++)
{
    z = x + y;
    x = y;
    y = z;
    cout << y << endl;

    if (y % 2 == 0)
    {
        sumeven += y;
    }
}
cout << "The total is: "<< sumeven << endl;
return 0;
}

这是我对上述代码的输出:

1
2
3
5
8
The total is: 10
Program ended with exit code: 0

输入4,000,000值时会出现问题。这是代码。唯一的区别是我没有打印序列。

#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 1, z, sumeven = 0;

for (int stop=1; stop <= 4000000; stop++)
{
    z = x + y;
    x = y;
    y = z;

    if (y % 2 == 0)
    {
        sumeven += y;
    }
}
cout << "The total is: "<< sumeven << endl;
return 0;
}

这是上述代码的输出。

The total is: -1833689714
Program ended with exit code: 0

我不明白为什么我的代码似乎与较小的序列完美配合,但在代码完全相同时没有输入400万。

我刚开始在uni编程桥接课程,以获得计算机科学的快速学位。他们在2个周末填补了一个学期的课程,并且我希望能够在最后阶段胜任C ++的基础知识,所以非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

你错误地解释了这个问题。您需要检查斐波那契序列的第4.000.000个元素,而问题要求的元素低于4.000.000

只需更改

for (int stop=1; stop <= 4000000; stop++)

while(y < 4000000)

编辑: 如果你不理解为什么数字是负数,那就是整数溢出的情况: https://en.wikipedia.org/wiki/Integer_overflow

相关问题