我想弄清楚如何我可以在while循環中設置一個條件語句,該條件語句將獲取所需斐波那契數的用戶輸入並計算相應的fib數。用戶輸入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'?編譯器是否給你提供任何警告? – CiaPan 2014-10-17 05:43:02
我做了編譯,當我輸入1時它無限運行。我無法想出一個可行的條件。對於-888,有一個警告,代碼永遠不會執行,我更多的是作爲一個佔位符,以便我可以在完成請求fib數後讓用戶退出循環。 – Nebulan 2014-10-17 06:06:05
作爲@ P0W或@ChantryCargill寫道:減少你的'fib'索引,以便你知道當索引變爲零時你應該停止。但在循環之前測試它的'-888'(或任何負值),所以你不會重複遞減一個負值... – CiaPan 2014-10-17 06:14:09