用遞迴尋找斐波那契數的 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++;
}

更新時間: 2023 年 9 月 6 日

61K+ 次瀏覽

開啟您的職業生涯

完成課程認證

開始
廣告
© . All rights reserved.