include iostream using namespace std int maxint int


















- Slides: 18
函數的用法 /* 傳回較大值 */ #include <iostream> using namespace std; int max(int, int); /* 宣告函數max() */ int main(void) { int a, b; cout << "First number: "; /*輸入兩個整數*/ cin >> a; cout << "Second number: "; cin >> b; cout << "The larger number is " << max(a, b) << endl; /*印出較大值*/ return 0; } int max(int i, int j)/* 自訂函數max(), 傳回較大值 */ { if (i>j) return i; else return j; } return i or j a b 7 9 max( a, b ) 7 9 i j 9
函數的寫法 /* 傳回較大值 */ #include <iostream> using namespace std; int max(int, int); /*宣告函數max()*/ int main(void) { int a, b; cout << "First number: "; /*輸入兩個整數*/ cin >> a; cout << "Second number: "; cin >> b; cout << "The larger number is " << max(a, b) << endl; /*印出較大值*/ return 0; } int max(int i, int j) /*自訂函數max(), 傳回較大值*/ { if (i>j) return i; else return j; }
函數的宣告 /* 傳回較大值 */ #include <iostream> using namespace std; int max(int, int); /*宣告函數max()*/ int main(void) { int a, b; cout << "First number: "; /*輸入兩個整數*/ cin >> a; cout << "Second number: "; cin >> b; cout << "The larger number is " << max(a, b) << endl; /*印出較大值*/ return 0; } int max(int i, int j) { if (i > j) return i; else return j; } /* 自訂函數max(), 傳回較大值 */
其他範例—求兩數相加 /* 兩數相加 */ #include <iostream> using namespace std; (2) int add(int, int); /* 宣告函數add() */ int main(void) { int a, b; (1) cout << "First number : "; /* 輸入兩個整數 */ cin >> a; cout << "Second number : "; cin >> b; cout << "The sum of " << a << " and " << b << " is " << return 0; add(a, b) << endl; /*印出sum值*/ } (3) int add(int num 1, int num 2) { int sum; sum = num 1 + num 2; return sum; } /* 自訂函數add(), 傳回兩數的和 */
其他範例—求最大公因數 /* 最大公因數 */ #include <iostream> using namespace std; int gcd(int, int); /* 宣告函數gcd() */ int main(void) { int a, b; cout << "First number : "; /* 輸入兩個整數 */ cin >> a; cout << "Second number : "; cin >> b; cout << "The GCD of " << a << " and " << b << " is " << gcd(a, b) <<endl; /*印出gcd值*/ return 0; } int gcd(int i, int j) { int g; while(j!=0) { g=i%j; i=j; j=g; } return i; } /* 自訂的函數gcd(), 傳回最大公因數 */
(2) (1) (3) #include <iostream> using namespace std; int fib(int); //宣告fib函數的型態 int main(void) //主程式 { int N, i; cout << "N = ? "; cin >> N; for (i=1; i<=N; i++) cout << fib(i) << endl ; return 0; } int fib(int n) { if (n==1 || n==2) return 1; else return (fib(n-1) + fib(n-2)); } //循序印出f(1) 到 f(n) //定義fib(n) //函數的Ending 值設定 //函數的一般值設定
F(6) F(4) F(5) F(4) F(3) F(2) 1 F(1) F(3) F(2) F(1) F(2) 1 1 F(2) F(1) 1 看f(6)的執行序 1 1
看f(6)的執行序 n if(n==1 || n==2) Return 結果 6 false F(5)+f(4) 8 5 false F(4)+f(3) 5 4 false F(3)+f(2) 3 3 false F(2)+f(1) 2 2 true 1 1 1 true 1 1