C++ 试图在c+;中的fibonacci循环中获得低于输入数的fibonacci数+;
我正在尝试构建一个程序,要求用户输入一个数字“k”,并打印一系列低于k的数字。 例如,如果用户写入C++ 试图在c+;中的fibonacci循环中获得低于输入数的fibonacci数+;,c++,function,loops,recursion,fibonacci,C++,Function,Loops,Recursion,Fibonacci,我正在尝试构建一个程序,要求用户输入一个数字“k”,并打印一系列低于k的数字。 例如,如果用户写入20,则输出必须为: 0, 1, 1, 2, 3, 5, 8, 13 相反,我得到了: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181 这意味着正在打印20个斐波那契数 #include <iostream> using std::cin; using std::c
20
,则输出必须为:
0, 1, 1, 2, 3, 5, 8, 13
相反,我得到了:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181
这意味着正在打印20个斐波那契数
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
unsigned int fib(unsigned int num)
{
if (num == 0 || num == 1)
{
return num;
}
else
{
return (fib(num - 1) + fib(num - 2));
}
}
int main()
{
int k = 0;
cout << "White a number k ";
cin >> k;
for (int i = 0; i < k; i++)
cout << fib(i) << endl;
return 0;
}
#包括
使用std::cin;
使用std::cout;
使用std::endl;
无符号整数fib(无符号整数num)
{
如果(num==0 | | num==1)
{
返回num;
}
其他的
{
返回(fib(num-1)+fib(num-2));
}
}
int main()
{
int k=0;
cout>k;
for(int i=0;i coutfor(int i=0;i您正在将输入的k
限制与迭代器i
进行比较,因此输入被读取为您想要输出的斐波那契序列中的数字数量,而不是上限
要执行您想要的操作,您需要将limitk
与fib
函数返回的结果进行比较,以便在超出限制后立即停止循环
保持for
循环:
int main()
{
int k = 0;
int res = 0; // store the result of fib(i) to avoid duplicate calls
cout << "White a number k: ";
cin >> k;
for (int i = 0; (res = fib(i)) < k; i++){ //assign fib(i) to res
cout << res << endl; //when res is larger than k exits the loop
}
return 0;
}
int main()
{
int k = 0;
cout << "White a number k: ";
cin >> k;
int res;
int i = 0; //iterator
while((res = fib(i++)) < k) { //assign result to res and compare it with the limit k
cout << res << endl; //output the result while it's smaller than k
}
return 0;
}
样本运行:
白色数字k:20
0
1.
1.
2.
3.
5.
8.
13
break
确实是一个解决方案。向我们展示您如何尝试使用它。请展示已损坏的代码,而不是正在工作的代码。我想您没有将{}
添加到循环中,但这只是一个猜测
int main()
{
int k = 0;
cout << "White a number k: ";
cin >> k;
int res;
int i = 0; //iterator
while((res = fib(i++)) < k) { //assign result to res and compare it with the limit k
cout << res << endl; //output the result while it's smaller than k
}
return 0;
}