返回列表 發帖

函數的建立與執行 (一)

本帖最後由 tonyh 於 2012-6-2 16:52 編輯

建立一自定函數, 使在程式中帶入便可執行.
本次練習所要執行的任務為: 計算任兩個正整數間, 所有數的總合.
  1. #include<iostream>
  2. using namespace std;
  3. int my_sum(int, int); //宣告一自訂函數
  4. int main()   //主程式
  5. {
  6.     int x, y;
  7.     cout<<"請輸入第一個數: ";
  8.     cin>>x;
  9.     cout<<"請輸入第二個數: ";
  10.     cin>>y;
  11.     cout<<"兩數間所有數的總合為"<<my_sum(x, y)<<endl;
  12.     system("pause");
  13.     return 0;
  14. }
  15. int my_sum(int x, int y)   //副程式
  16. {
  17.     int total=0, temp;
  18.     if(y<x)
  19.     {
  20.         temp=y;
  21.         y=x;
  22.         x=temp;
  23.     }
  24.     for(int i=x; i<=y; i++)
  25.     {
  26.         total=total+i;
  27.     }
  28.     return total;    //將值回傳
  29. }
複製代碼

返回列表