我在 C++ 中对 Project Euler 的 #2 的解决方案有什么问题?

What's wrong with my solution to Project Euler's #2 in C++?

这是问题:

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, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

当我 运行 下面的程序给了我

-1833689714

有人可以帮我解决代码问题吗?

============================================= ===========================

#include <iostream>
using namespace std;
int fibona (int k);
int first = 0 , second = 1 , fibo = 0, sum = 0;

int main()
{
cout << "Sum of even values less than 4000000 : " ;
fibona (4000000);
}



int fibona (int k)
{
for (int c = 0 ; c < k ; c++)
{

    if (c <= 1)
    {
        fibo = c;
    }
    else
    {
        fibo = first + second;
        first = second;
        second = fibo;
    }
    if (fibo % 2 == 0)
    {

        sum += fibo;

    }

}



cout << sum <<endl;

}

你知道Fib(4000000)多少钱吗?

必须大约

((1+Sqrt[5])/2)^4000000/Sqrt[5] = 1.627477... × 10^835950

无法将其放入任何变量类型。

#include <iostream>
using namespace std;
long fibona_even_sum (long k);

int main()
{
    const long N=4000000;
    cout << "Sum of even Fibonacci numbers: " <<endl;
    cout << fibona_even_sum(N) <<endl;
}

long fibona_even_sum(long N_max)
{
    long first = 0 , second = 1;
    long sum=0;

    while(true)
    {
        long first_copy=first;
        first=second;
        second+=first_copy;
        if(second>N_max)
            return sum;
        if(!(second%2))
            sum+=second;
    }
}

在上面的代码中,您可以将所有 long 更改为 int。效果很好。