使用 while 循环计算前 n 个斐波那契数的程序
当我运行它并输入一个数字时,它只是不停地重复它。例如,如果我输入 3,它将执行此操作 3 3 3 3 3 但永不停歇
int main()
{
int current=0, prev=1, prev2=1, fibnum;
cout << "Enter the number of Fibonacci numbers to compute: ";
cin >> fibnum;
if (fibnum <=0)
{
cout << "Error: Enter a positive number: ";
}
while (fibnum > 0){
current = prev + prev2;
prev = prev2;
prev2 = current;
current++;
cout << "," << fibnum;
cout << endl;
}
return 0;
}
When I run it and input a number it just repeats it over non-stop. for example if i put a 3 it will do this
3
3
3
3
3
BUT NON STOP
int main()
{
int current=0, prev=1, prev2=1, fibnum;
cout << "Enter the number of Fibonacci numbers to compute: ";
cin >> fibnum;
if (fibnum <=0)
{
cout << "Error: Enter a positive number: ";
}
while (fibnum > 0){
current = prev + prev2;
prev = prev2;
prev2 = current;
current++;
cout << "," << fibnum;
cout << endl;
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(8)
千纸鹤带着心事2024-12-14 06:58:33
#include <iostream>
using namespace std;
int main(){
int current=0, prev=0, prev2=1, fibnum;
cout << "Enter the number of Fibonacci numbers to compute: ";
cin >> fibnum;
if (fibnum <=0){
cout << "Error: Enter a positive number: ";
}
while (fibnum--){
cout << prev ;
current = prev + prev2;
prev = prev2;
prev2 = current;
if(fibnum)
cout << ",";
}
cout << endl;
return 0;
}
终止放荡2024-12-14 06:58:33
#include <iostream>
using std::cin;
using std::cout;
int main()
{
int a=1, b=1, nums_to_print;
while (1) {
cout << "Enter the number of Fibonacci numbers to compute: ";
cin >> nums_to_print;
if (nums_to_print > 0) {
while (1) {
cout << a;
b += a;
a = b - a;
if (--nums_to_print) cout << ",";
else break;
}
cout << "\n";
return 0;
}
cout << "Error: Enter a positive number.\n";
}
}
彻夜缠绵2024-12-14 06:58:33
您需要解决一些问题。
你需要有一个计数变量;
int current=0, prev=0, prev2=1, fibnum;
int count;
....
要在循环之前输出第一个数字
cout<<prev2;
您可以将其更改为 for 循环,以便更轻松地计算数字
for(count = 0; count <= fibnum; count++){
current = prev + prev2;
prev = prev2;
prev2 = current;
您需要打印 current,而不是 fibnum -> fibnum 是您需要打印的总数
cout << "," << current;
}
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
该代码存在几个问题:
current++
的目的完全不清楚。基本上,您需要确定每个变量的确切含义,并始终坚持它。从这些变量的使用方式来看,
current
和fibnum
的用途显然存在混淆。There are several problems with the code:
fibnum
inside the body of the loop, so its value never changes.current++
is entirely unclear.Basically, you need to decide on the exact meaning of every variable, and stick to it throughout. The way these variables are being used, there's clearly confusion around the purpose of
current
andfibnum
.