返回列表 發帖

遞迴函式 (三) - 計算總和

本帖最後由 tonyh 於 2014-3-22 14:23 編輯

利用函式遞迴法, 自建 total() 函式, 分別計算
1+2+3+...+5= ?
1+2+3+...+100= ?
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int total(int);
  5. int main()
  6. {
  7.     cout<<"1+2+3+...+5="<<total(5)<<endl;
  8.     cout<<"1+2+3+...+100="<<total(100)<<endl;
  9.     system("pause");   
  10.     return 0;
  11. }
  12. int total(int x)
  13. {
  14.     if(x<=1)
  15.         return x;
  16.     else
  17.         return x+total(x-1);
  18. }
  19. /*
  20.      total(5)=5+total(4)
  21.              =5+4+total(3)
  22.              =5+4+3+total(2)
  23.              =5+4+3+2+total(1)
  24.              =5+4+3+2+1
  25. */
複製代碼

返回列表