# C++函式(funtion) #### 教學:楊博鈞 --- # 什麼是函式? ---- ### 在數學中的函式就像一台機器 ### 在程式中的函式就像一台複雜的機器 ---- ![](https://hackmd.io/_uploads/SyVhuu9e6.png) #### 來源:網路 --- # 函式結構 ---- ```cpp= type name(...) { // do something return something; } ``` ---- ## 範例 ```cpp= int add(int a, int b) { int c = a + b; return c; } ``` --- # 函式宣告 ---- ## 方法1 ```cpp= int f(); //在此宣告 int main(){     f(); } int f(){         //do something } //先宣告後定義函式 ``` ---- ## 方法2 ```cpp= int f(){         //do something } int main(){     f();   } //宣告同時定義函式 ``` ---- #### 除了void以外型態的函數,都必須有return值。 ```cpp= //錯誤的宣告 int add(int a, int b){ int c = a + b; //缺少return值 } ``` ---- #### 函數return的值必須與宣告的型態相同 ```cpp= //錯誤的宣告 int add(int a, int b){ float c = a + b; return c; //型態不一致 } ``` ---- ### Void ```cpp= void print(int a, int b){ cout << a + b << endl; return; //不須回傳值 } ``` --- # 函式的作用 ---- ### 就只是把main函式的程式碼拿出來 --- # 函式的其他應用 ---- ## 遞迴(下一節課會講) --- # 常用的內建函式 ---- | 標頭檔 | <algorithm>| | ------ | -------- | | swap() | 交換兩個變數 | | min() | 取兩個數的較小值 | | max() | 取兩個數的較大值 | | 標頭檔 | <cmath>| | -------- | -------- | | pow() | 計算一個數的冪 | | sqrt() | 計算一個數的根 | | abs() | 計算一個數的絕對值 | |log() | 計算一個數的自然對數 | --- # 練習題 ---- # CSDC 165 # CSDC 336 ---- ## CSDC 165 ```cpp= #include <iostream> using namespace std; //Do not modify above void solve(int n) { // Complete this function //修改這裡來作答!!! 這個Function以外的都不要動 for(int i = n ; i >= 1 ; i--) cout << i << endl; for(int i = 2 ; i <=n ; i++) cout << i << endl; } // Do not modify below int main() { int n; cin >> n; solve(n); } ``` ---- ## CSDC 336 ```cpp= #include <iostream> using namespace std; int foo(int); int bar(int); int main() { string str; int n; while(cin >> str >> n){ int ans; if(str=="foo") ans=foo(n); else ans=bar(n); cout << ans << endl; } } int foo(int x){ if(x < 0) return 0; else if(x <= 5) return x; return bar(x-10); } int bar(int x){ if(x < 0) return 0; else if(x<=10) return x; return foo(x-5); } ```
{"title":"函式","description":"type: slide","contributors":"[{\"id\":\"8b61a27e-159d-4386-a2e4-e9ff3c2e6c6e\",\"add\":2923,\"del\":597}]"}
    199 views