下面的程序是求不超过四百万的偶数斐波那契数项之和。 该程序中的最后一个“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;
}
最佳答案
我无法执行该程序,但我认为您的程序永远不会结束,这就是为什么您永远无法执行该语句的原因。你的外衣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;
}
关于c++ - 'cout' 语句未被执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28345446/