使用迭代查找斐波那契数的 C++ 程序
以下是一个通过迭代查找斐波那契数的示例。
示例
#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(),如下一行所示打印斐波那契数列 −
cout << "Enter the number : "; cin >> num; cout << "\nThe fibonacci series : " ; fib(num);
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP