【发布时间】:2014-10-17 05:09:09
【问题描述】:
我试图弄清楚如何在 while 循环中设置一个条件语句,该语句将接受用户输入所需的斐波那契数并计算相应的斐波那契数。用户输入 8 和程序输出 34。任何可以指出我正确方向或帮助我从不同角度看待问题的提示将不胜感激。
#include <iostream>
using namespace std;
int main ()
{
bool exit;
int fib;
int fib1 = 1;
int fib2 = 2;
int fib3 = 0;
cout << "The first Fibonacci number is 1" << endl;
cout << "The second Fibonacci number is 2" << endl;
cout << "what other Fibonacci number would you like? Enter -888 to exit: ";
cin >> fib;
while(fib ) //condition that makes sure output is the fibonacci the user is looking for
{
fib3 = (fib1+fib2);
fib1 = fib2;
fib2 = fib3;
cout << "...and the Fibonnaci is..... " << fib << endl;
}
if(fib == -888)
{
exit = true;
}
return 0;
}
【问题讨论】:
-
您是否编译并运行了程序?当您输入
1时,它的行为如何?对于-888?编译器有没有给你任何警告? -
我确实编译了,当我输入 1 时它会无限运行。我一直无法想出一个有效的条件。对于 -888 有一个警告,代码永远不会执行,我更多地把它作为一个占位符,说明如何让用户在完成询问 fib 数字后退出循环。
-
Do as @P0W 或@ChantryCargill 写道:减少您的
fib索引,以便您知道当索引变为零时您将停止。但是在循环之前测试它的-888(或任何负值),这样你就不会陷入重复递减负值...