用遞迴尋找斐波那契數的 C++ 程式
下面是使用遞迴的斐波那契數列示例。
示例
#include <iostream> using namespace std; int fib(int x) { if((x==1)||(x==0)) { return(x); }else { return(fib(x-1)+fib(x-2)); } } int main() { int x , i=0; cout << "Enter the number of terms of series : "; cin >> x; cout << "\nFibonnaci Series : "; while(i < x) { cout << " " << fib(i); i++; } return 0; }
輸出
Enter the number of terms of series : 15 Fibonnaci Series : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
上述程式中,實際程式碼包含在函式‘fib’中,如下所示:
if((x==1)||(x==0)) { return(x); }else { return(fib(x-1)+fib(x-2)); }
在 main() 函式中,使用者輸入項數,並呼叫 fib()。斐波那契數列如下所示。
cout << "Enter the number of terms of series : "; cin >> x; cout << "\nFibonnaci Series : "; while(i < x) { cout << " " << fib(i); i++; }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP