返回列表 發帖

函式的建立與執行 (六) - 計算累加(遞迴)

本帖最後由 鄭繼威 於 2024-1-15 21:04 編輯

計算 1 加到 n.

先看之前用for 迴圈
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;

  4. int myPlus(int a)
  5. {
  6.         if(a==1)
  7.         {
  8.                 return 1;
  9.         }
  10.     return a+myPlus(a-1);
  11. }

  12. int main()
  13. {
  14.    
  15.     int a;
  16.    
  17.     cout<<"1+...+?:";
  18.     cin>>a;

  19.    
  20.     cout<<1<<"+...+"<<a<<"="<<myPlus(a)<<endl;
  21.                
  22.     system("pause");
  23.     return 0;
  24. }
複製代碼

此帖僅作者可見

TOP

此帖僅作者可見
Attention seeker 101!

TOP

此帖僅作者可見

TOP

此帖僅作者可見

TOP

返回列表