使用 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)
该代码存在几个问题:
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
.更改为
change to
除了前面的答案之外,请注意,如果您需要计算具有某个特定数字的 fib 数,您可以使用递归的好处。类似的事情:
但您必须记住,这将导致冗余计算,因为相同数字的可重复重新计算以及用于传输函数参数的堆栈使用。
In addition to previous answers note that you can use benefits of recursion if you need to calculate fib number with some certain number. Something like that:
but you must keep in mind that this will lead to redundant calculations 'coz of repeatable recalc of same numbers and stack use for transmitting function args.
您正在尝试打印 fibnum,但它在 while 循环内没有改变。
您应该打印 current 。
您还需要设置一个计数器来查看 while 循环的结束。
You are trying to print fibnum, but it is not changing inside the while loop.
You should be printing current instead.
Also you need to set a counter that will see the end of while loop.
演示:http://ideone.com/3H8Fq
Demo: http://ideone.com/3H8Fq
您需要解决一些问题。
你需要有一个计数变量;
....
要在循环之前输出第一个数字
您可以将其更改为 for 循环,以便更轻松地计算数字
您需要打印 current,而不是 fibnum -> fibnum 是您需要打印的总数
There are a couple of things you need to fix.
You need to have a count variable;
....
To output the first number before the loop
You can change this to a for loop to make it easier to count the numbers
You need to print current, not fibnum -> fibnum is the total numbers that you need to print