返回列表 發帖

遞迴函式 (二) - 費氏數列

本帖最後由 tonyh 於 2014-3-15 15:36 編輯

費氏數列規則如下:
第n項 = 第 n-1 項  + 第 n-2 項

即整個費式數列為:
1 1 2 3 5 8 13 21 34 55 89 144 233 377...

利用函式遞迴法, 推算費氏數列中第N項的值.
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int calcu(int);
  5. int main()
  6. {
  7.     int x;
  8.     cout<<"請輸入欲推算的費氏數列項次: ";
  9.     cin>>x;
  10.     cout<<"費氏數列中, 第"<<x<<"個數的值為"<<calcu(x)<<endl<<endl;
  11.     system("pause");   
  12.     return 0;
  13. }
  14. int calcu(int x)
  15. {
  16.     if(x<=1)
  17.         return x;
  18.     else
  19.         return calcu(x-1)+calcu(x-2);
  20. }
複製代碼

返回列表