以下是使用迭代查找斐波那契数列的示例。
#include <iostream>
using namespace std;
void fib(int num) {
int x = 0, y = 1, z = 0;
for (int i = 0; i < num; i++) {
cout << x << " ";
z = x + y;
x = y;
y = z;
}
}
int main() {
int num;
cout << "Enter the number : ";
cin >> num;
cout << "\nThe fibonacci series : " ;
fib(num);
return 0;
}输出结果
Enter the number : 10 The fibonacci series : 0 1 1 2 3 5 8 13 21 34
在上述程序中,实际代码存在于函数fib()中,以计算斐波那契数列。
void fib(int num) {
int x = 0, y = 1, z = 0;
for (int i = 0; i < num; i++) {
cout << x << " ";
z = x + y;
x = y;
y = z;
}
}在main()函数中,用户输入数字。调用函数fib(),并按如下所示打印fibonacci系列-
cout << "Enter the number : "; cin >> num; cout << "\nThe fibonacci series : " ; fib(num);