使用迭代查詢斐波那契數的 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