我正在尝试构建一个程序,要求用户输入数字“ 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::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;
}
我尝试使用“ break;”但是是行不通的。如何打破循环?
for (int i=0; i<k; i++){
if(fib(i)<k) //while fib(i) is less than k,it prints fib(i)
cout << fib(i) << endl;
else //if number becomes greater than k,then it will break out from the loop.
break;
}
希望有帮助!!
您正在将输入的限制与迭代器i
进行比较,实际上您需要将其与斐波那契函数的结果进行比较,例如:
int main()
{
int k = 0;
cout << "White a number k ";
cin >> k;
int res, i = 0;
while((res = fib(i++)) < k) //assing the result to res and compare it with the limit k
cout << res << endl; //output the result while it's smaller than k
return 0;
}