【问题标题】:'cout' statement not being executed'cout' 语句未执行
【发布时间】:2015-02-05 13:40:59
【问题描述】:

下面的程序是找出不超过四百万的偶数斐波那契项的总和。 该程序中的最后一个“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;
}

【问题讨论】:

  • 你试过冲洗吗?
  • 你肯定有一个无限循环。
  • @stefan:是的。但由于这甚至不是真正的问题,我将删除评论。

标签: c++ cout fibonacci


【解决方案1】:

我无法执行该程序,但我认为您的程序永远不会结束,这就是为什么您永远不会到达该语句的原因。您的外部 while 循环将继续运行 unitl c &lt;= 4000000。然而,你只增加c当且仅当(a + b) &lt;= 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;
}

【讨论】:

  • 删除if ((a + b) &lt;= ...会更简单,程序仍然可以得到正确的结果。
  • @remyabel:是的,我同意。我试图给出一个对 OP 提供的修改较少的答案。
  • 顺便说一句,sum1 不是没用吗?
  • @Thomas:是的,我想是的。如果我正确理解这一点,代码应该给出一个答案,该答案被 sum1 关闭。
  • npinti 的解决方案是最好的 IMO。如果程序要打印所有不超过 400 万的斐波那契数,而不是仅使用偶数斐波那契数,他的解决方案将有效,但只需删除“if ((a+b)
【解决方案2】:
while ( c <= 4000000 )
{
    // ...
    if ( ( a + b ) <= 4000000 )
    {
        c = a + b;    // i.e. <= 4000000
        // ...
    }
}

您希望该循环如何终止?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-03
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多