我的任务是显示斐波那契数,但同时询问用户他/她希望在给定时间计算多少个数。
他们让我参考书中的一个例子。我以为代码中的几行更改就能解决我的问题,但我很难理解这段代码哪里出了问题。
int main()
{
int NumsToCal = 5;
cout << "How many numbers would you like to calculate?" << endl;
cin >> NumsToCal;
cout << " This program will calculate " << NumsToCal << " Fibonacci Numbers at a time" <<endl;
int Num1 = 0, Num2 = 1;
char WantMore = ' ';
cout << Num1 << " " << Num2 << " " ;
do
{
for( int Index = 0; Index < NumsToCal; ++Index)
{
cout << Num1 + Num2 << " ";
int Num2Temp = Num2;
Num2 = Num1 + Num2;
Num1 = Num2Temp;
}
cout << "Do you want more numbers (y/n)? " << endl;
cin >> WantMore;
} while (WantMore == 'y');
cout << "Goodbye!" << endl;
return 0;
}
Xsami是绝对正确的。你只需要再包括一行,比如:
cin>>NumstoCal;
尽管为了更清晰起见,改变输出内容的方式也不错。
这是我的代码:https://ideone.com/BXREP9
您唯一需要做的就是再次读取NumsToCal
,并且必须在cin >> WantMore;
之后执行类似操作
if ( WantMore == 'y' )
{
Num1 = 0;
Num2 = 1;
cout << "How many numbers would you like to calculate?" << endl;
cin >> NumsToCal;
cout << Num1 << " " << Num2 << " " ;
}
这是我的代码:http://ideone.com/a8um5Z