'cout'声明没有被执行

时间:2015-02-05 13:41:00

标签: c++ cout fibonacci

以下计划是找出偶数斐波纳契项的总和不超过四百万。 该程序中的最后一个'cout'语句根本没有被执行。为什么?请帮助。

#include <iostream>

using namespace std;

int main()
{
    int a, b, c, sum, sum1, sum2;
    a = 1;
    b = 2;
    sum2 = 0;

    cout << b << endl;
    c = a + b;

    sum1 = c;

    while (c <= 4000000)
    {
        a = b;
        b = c;
        if ((a + b) <= 4000000)
        {
            c = a + b;
            if (c%2 == 0)
            {
                sum2 = sum2 + c;
                cout << c << endl;
            }
        }
    }

    cout << "The sum of even fibonacci numbers not greater than 4 million is: " << (sum1 + sum2); //Not being executed
    return 0;
}

2 个答案:

答案 0 :(得分:5)

我无法执行该程序,但我认为您的程序永远不会结束,这就是您永远不会达到该声明的原因。您的外while循环将继续单元c <= 4000000。但是,当且仅当c时,您才会增加(a + b) <= 4000000,因此c永远不会超过400万。

要解决此问题,您可以尝试以下方法:

#include <iostream>

using namespace std;

int main()
{
    int a, b, c, sum, sum1, sum2;
    a = 1;
    b = 2;
    sum2 = 0;   

    cout << b << endl;
    c = a + b; 

    sum1 = c;

    while (c <= 4000000)
    {
        a = b;
        b = c;
        c = a + b; //Update c regardless.
        if (c <= 4000000)
        {           
            if (c%2 == 0)
            {
                sum2 = sum2 + c;
                cout << c << endl;
            }
        }
    }


    cout << "The sum of even fibonacci numbers not greater than 4 million is: " << (sum1 + sum2); //Not being executed
    return 0;
}

答案 1 :(得分:1)

while ( c <= 4000000 )
{
    // ...
    if ( ( a + b ) <= 4000000 )
    {
        c = a + b;    // i.e. <= 4000000
        // ...
    }
}

您如何期望该循环终止?