>num_1; cout<<" 輸入第二個數字 :"; cin>>num_2; cout<<" 相加等於 "< >num_1; cout<<" 輸入第二個數字 :"; cin>>num_2; cout<<" 相加等於 "<

Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2002 Pearson Education, Inc. Slide 1.

Similar presentations


Presentation on theme: "Copyright © 2002 Pearson Education, Inc. Slide 1."— Presentation transcript:

1 Copyright © 2002 Pearson Education, Inc. Slide 1

2 Copyright © 2002 Pearson Education, Inc. Slide 2 Chapter Created by Frederick H. Colclough, Colorado Technical University Function Basics

3 Copyright © 2002 Pearson Education, Inc. Slide 3 int main(void) { double num_1,num_2; cout<<" 輸入第一個數字 :"; cin>>num_1; cout<<" 輸入第二個數字 :"; cin>>num_2; cout<<" 相加等於 "<<sum(num_1,num_2)<<endl; return 0; } double sum(double a,double b) { Return a+b; } 函數 主程式

4 Copyright © 2002 Pearson Education, Inc. Slide 4 Programmer-Defined Functions  Write your own functions!  Building blocks of programs  Divide & Conquer  Readability  Re-use  Your ‘definition’ can go in either:  Same file as main()  Separate file so others can use it, too

5 Copyright © 2002 Pearson Education, Inc. Slide 5 Components of Function Use  3 Pieces to using functions:  Function Declaration/prototype  Information for compiler  To properly interpret calls  Function Definition  Actual implementation/code for what function does  Function Call  Transfer control to function

6 Copyright © 2002 Pearson Education, Inc. Slide 6 Function Declaration  Also called function prototoype  An ‘informational’ declaration for compiler  Tells compiler how to interpret calls  Syntax: FnName( );  Example: double totalCost(int numberParameter, double priceParameter);  Placed before any calls  In declaration space of main()  Or above main() in global space

7 Copyright © 2002 Pearson Education, Inc. Slide 7 Function Definition  Implementation of function  Just like implementing function main()  Example: double totalCost(int numberParameter, double priceParameter) { const double TAXRATE = 0.05; double subTotal; subtotal = priceParameter * numberParameter; return (subtotal + subtotal * TAXRATE); }  Notice proper indenting

8 Copyright © 2002 Pearson Education, Inc. Slide 8 Function Definition Placement  Placed after function main()  NOT ‘inside’ function main()!  Functions are ‘equals’; no function is ever ‘part’ of another  Formal parameters in definition  ‘Placeholders’ for data sent in  ‘Variable name’ used to refer to data in definition  return statement  Sends data back to caller

9 Copyright © 2002 Pearson Education, Inc. Slide 9 Function Call  Just like calling predefined function bill = totalCost(number, price);  Recall: totalCost returns double value  Assigned to variable named ‘bill’  Arguments here: number, price  Recall arguments can be literals, variables, expressions, or combination  In function call, arguments often called ‘actual arguments’  Because they contain the ‘actual data’ being sent

10 Copyright © 2002 Pearson Education, Inc. Slide 10 Parameter vs. Argument  Terms often used interchangeably  Formal parameters/arguments  In function declaration  In function definition’s header  Actual parameters/arguments  In function call  Technically parameter is ‘formal’ piece while argument is ‘actual’ piece*  *Terms not always used this way

11 Copyright © 2002 Pearson Education, Inc. Slide 11 Boolean Return-Type Functions  Return-type can be any valid type  Given function declaration/prototype: bool appropriate(int rate);  And function’s definition: bool appropriate (int rate) { return (((rate>=10)&&(rate<20))||(rate==0); }  Returns ‘true’ or ‘false’  Function call, from some other function: if (appropriate(entered_rate)) cout << “Rate is valid\n”;

12 Copyright © 2002 Pearson Education, Inc. Slide 12 #include using namespace std; double sum(double,double); // 回傳函數型態 函數名稱 ( 資料型態, 資料型態,...) int main(void) { double num_1,num_2; cout<<" 輸入第一個數字 :"; cin>>num_1; cout<<" 輸入第二個數字 :"; cin>>num_2; cout<<" 相加等於 "<<sum(num_1,num_2)<<endl; return 0; } double sum(double a,double b) // 回傳型態 函數名稱 ( 資料型態 參數一, 資料型態 參數二 ) { return a+b; // 回傳值 }

13 Copyright © 2002 Pearson Education, Inc. Slide 13 #include using namespace std; double sum(double a,double b) // 回傳型態 函數名稱 ( 資料型態 參數一, 資料型態 參數二 ) { return a+b; // 回傳值 } int main(void) { double num_1,num_2; cout<<" 輸入第一個數字 :"; cin>>num_1; cout<<" 輸入第二個數字 :"; cin>>num_2; cout<<" 相加等於 "<<sum(num_1,num_2)<<endl; return 0; }

14 Copyright © 2002 Pearson Education, Inc. Slide 14 #include using namespace std; int main(void) { double sum(double,double); // 回傳函數型態 函數名稱 ( 資料型態, 資料型態,...) double num_1,num_2; cout<<" 輸入第一個數字 :"; cin>>num_1; cout<<" 輸入第二個數字 :"; cin>>num_2; cout<<" 相加等於 "<<sum(num_1,num_2)<<endl; return 0; } double sum(double a,double b) // 回傳型態 函數名稱 ( 資料型態 參數一, 資料型態 參數二 ) { return a+b; // 回傳值 }

15 Copyright © 2002 Pearson Education, Inc. Slide 15 函數型態 回傳函數型態 函數名稱 ( 資料型態, 資料型態,...) 回傳型態可以是各種型態 double power(double,int); 限制傳入函數的數字可以為小數, 但是次方數必須為整數  power(3,2.5) 會出現問題

16 Copyright © 2002 Pearson Education, Inc. Slide 16 Declaring Void Functions  Similar to functions returning a value  Return type specified as ‘void’  Example:  Function declaration/prototype: void showResults(double fDegrees, double cDegrees);  Return-type is ‘void’  Nothing is returned

17 Copyright © 2002 Pearson Education, Inc. Slide 17 Declaring Void Functions  Function definition: void showResults(double fDegrees, double cDegrees) { cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(1); cout << fDegrees << “ degrees fahrenheit equals \n” << cDegrees << “ degrees celsius.\n”; }  Notice: no return statement  Optional for void functions

18 Copyright © 2002 Pearson Education, Inc. Slide 18 Calling Void Functions  Same as calling predefined void functions  From some other function, like main():  showResults(degreesF, degreesC);  showResults(32.5, 0.3);  Notice no assignment, since no value returned  Actual arguments (degreesF, degreesC)  Passed to function  Function is called to ‘do it’s job’ with the data passed in

19 Copyright © 2002 Pearson Education, Inc. Slide 19 函數型態 void :表示此函數不需要傳值 若函數宣告為 double sum_1_100(void);  sum_1_100 函數不需要傳入值 若函數宣告為 void show_sum(double num_1,double num_2)  show_sum 函數不需要回傳值

20 Copyright © 2002 Pearson Education, Inc. Slide 20 #include using namespace std; double sum_1_100(void); int main(void) { double num; num=sum_1_100(); cout<<"1 到 100 的和為 "<<num<<endl; return 0; } double sum_1_100(void) { double answer=0; for(int i=1;i<=100;i++) { answer=answer+i; } return answer; } 傳入值為 void 不需要傳入值 傳回值 為 double 型態

21 Copyright © 2002 Pearson Education, Inc. Slide 21 #include using namespace std; void show_sum(double,double); int main(void) { double num_1,num_2; cout<<" 輸入第一個數字 "; cin>>num_1; cout<<" 輸入第二個數字 "; cin>>num_2; show_sum(num_1,num_2); return 0; } void show_sum(double a,double b) { cout<<" 兩數相加 ="<<a+b<<endl; } 傳入值為 double 型態 不需要回 傳值 沒有 return 值

22 Copyright © 2002 Pearson Education, Inc. Slide 22 #include using namespace std; void show_1(void); void show_2(void); int main(void) { cout<<"Section in Main(),first"<<endl; show_1(); cout<<"Section in Main(),second"<<endl; return 0; } void show_1(void) { cout<<"Section in show_1(),first"<<endl; show_2(); cout<<"Section in show_1(),second"<<endl; } void show_2(void) { cout<<"Section in show_2()"<<endl; } 執行結果 : Section in Main(),first Section in show_1(),first Section in show_2(),first Section in show_1(),second Section in Main(),second

23 Copyright © 2002 Pearson Education, Inc. Slide 23 Global Constants and Global Variables  Declared ‘outside’ function body  Global to all functions in that file  Declared ‘inside’ function body  Local to that function  Global declarations typical for constants:  const double TAXRATE = 0.05;  Declare globally so all functions have scope  Global variables?  Possible, but SELDOM-USED  Dangerous: no control over usage!

24 Copyright © 2002 Pearson Education, Inc. Slide 24 Scope Rules  Local variables  Declared inside body of given function  Available only within that function  Can have variables with same names declared in different functions  Scope is local: ‘that function is it’s scope’  Local variables preferred  Maintain individual control over data  Need to know basis  Functions should declare whatever local data needed to ‘do their job’

25 Copyright © 2002 Pearson Education, Inc. Slide 25 #include using namespace std; char char_1[]="Ya~"; void showChar_1(void); int main(void) { char char_2[]=“My God~"; showChar_1(); return 0; } void showChar_1(void) { cout<<char_1<<endl; } 全域變數 區域變數 char_1 為全域變 數, 不需要再次宣 告

26 Copyright © 2002 Pearson Education, Inc. Slide 26 #include using namespace std; double sum(double,double); // 回傳函數型態 函數名稱 ( 資料型態, 資料型態,...) int main(void) { double num_1,num_2; cout<<" 輸入第一個數字 :"; cin>>num_1; cout<<" 輸入第二個數字 :"; cin>>num_2; cout<<" 相加等於 "<<sum(num_1,num_2)<<endl; return 0; } double sum(double num_1,double num_2) { return num_1+num_2; // 回傳值 } 為區域變數, 兩變數處於 不同的區域 函數,故變 數名稱可以 相同

27 Copyright © 2002 Pearson Education, Inc. Slide 27 #include using namespace std; double sum(double,double); // 回傳函數型態 函數名稱 ( 資料型態, 資料型態,...) double num_1=2.2,num_2=1.1; double num_3=0.5; void main(void) { double num_4; cout<<“num_1=“<<num_1<<endl; cout<<“num_2=“<<num_2<<endl; cout<<"num_3="<<num_3<<endl; num_4=sum(num_1,num_2); cout<<" 相加等於 "<<num_4<<endl; cout<<"num_3="<<num_3<<endl; } double sum(double a,double b) { double num_3; num_3=a+b; cout<<"num_3 in sum is "<<num_3<<endl; return num_3; } num_1,num_2, num_3 為全域 變 數, 此 num_3 為區 域 變數 執行結果 : num_1=2.2 num_2=1.1 num_3=0.5 num_3 in sum is 3.3 相加等於 3.3 num_3=0.5

28 Copyright © 2002 Pearson Education, Inc. Slide 28 #include using namespace std; void local(void); // 回傳函數型態 函數名稱 ( 資料型態, 資料型態,...) double num_1=2.2,num_2=1.1; void main(void) { cout<<“num_1=“<<num_1<<endl; cout<<“num_2=“<<num_2<<endl; local(); cout<<“num_1=“<<num_1<<endl; cout<<“num_2=“<<num_2<<endl; } void local(void) { num_1=num_1+1; num_2=num_2-1; cout<<“num_1 in local is “<<num_1<<endl; cout<<“num_2 in local is “<<num_2<<endl; } num_1,num_2, 為全域變數 num_1,num_2, 為全域變數 執行結果 : num_1=2.2 num_2=1.1 num_1 in local is 3.2 num_1=3.2 num_2=0.1 num_2 in local is 0.1

29 Copyright © 2002 Pearson Education, Inc. Slide 29 Random Number Generator  Return ‘randomly chosen’ number  Used for simulations, games  rand()  Takes no arguments  Returns value between 0 & RAND_MAX  Scaling  Squeezes random number into smaller range rand() % 6  Returns random value between 0 & 5  Shifting rand() % 6 + 1  Shifts range between 1 & 6 (e.g.: die roll)

30 Copyright © 2002 Pearson Education, Inc. Slide 30 Random Number Seed  Pseudorandom numbers  Calls to rand() produce given ‘sequence’ of random numbers  Use ‘seed’ to alter sequence srand(seed_value);  void function  Receives one argument, the ‘seed’  Can use any seed value, including system time: srand(time(0));  time() returns system time as numeric value  Library contains time() functions

31 Copyright © 2002 Pearson Education, Inc. Slide 31 Random Examples  Random double between 0.0 & 1.0: (RAND_MAX – rand())/static_cast (RAND_MAX)  Type cast used to force double-precision division  Random int between 1 & 6: rand() % 6 + 1  ‘%’ is modulus operator (remainder)  Random int between 10 & 20: rand() % 10 + 10

32 Copyright © 2002 Pearson Education, Inc. Slide 32 #include using namespace std; void main(void) { srand(time(NULL)); int num[5]; for(int i=0;i<=4;i++) { num[i]=rand()%1000; } for(int i =0;i<=4;i++) { cout<<num[i]<<endl; } 亂數函式 取 0~10 00 的亂數

33 Copyright © 2002 Pearson Education, Inc. Slide 33 Predefined Void Functions  No returned value  Performs an action, but sends no ‘answer’  When called, it’s a statement itself  exit(1);// No return value, so not assigned  This call terminates program  void functions can still have arguments  All aspects same as functions that ‘return a value’  They just don’t return a value!

34 Copyright © 2002 Pearson Education, Inc. Slide 34 #include using namespace std; double power(double,double); int main(void) { double num_1,num_2; cout<<" 輸入數字 :"; cin>>num_1; cout<<" 輸入次方 :"; cin>>num_2; cout<<power(num_1,num_2)<<endl; return 0; } double power(double a,double b) { double answer=1.0; if(b<0) exit(0); for(int i=1;i<=b;i++) { answer=answer*a; } return answer; } 次方數小於 0 , 不回傳值 exit 用法

35 Copyright © 2002 Pearson Education, Inc. Slide 35 傳值、傳址、傳參考的比較 傳值呼叫傳址呼叫傳參考呼叫 原型宣告 void swap(int,int);void swap(int *,int *);void swap(int &,int &); 函數呼叫 swap(num_1,num_2);swap(&num_1,&num_2);swap(num_1,num_2); 函數宣告 void swap(int a,int b)void swap(int *a,int *b)void swap(int &a,int &b) 參數是 否改變 否是是

36 Copyright © 2002 Pearson Education, Inc. Slide 36 #include using namespace std; void swap(int,int); void main(void) { int num_1=100,num_2=1; cout<<"before function call "<<endl; cout<<"num_1="<<num_1<<endl; cout<<"num_2="<<num_2<<endl; swap(num_1,num_2); cout<<endl; cout<<"after function call "<<endl; cout<<"num_1="<<num_1<<endl; cout<<"num_2="<<num_2<<endl; } void swap(int a,int b) { int temp; temp=a; a=b; b=temp; } 執行結果: before function call num_1=100 num_2=1 after function call num_1=100 num_2=1 Call By Value ( 傳值呼叫 )

37 Copyright © 2002 Pearson Education, Inc. Slide 37 #include using namespace std; void swap(int *,int *); void main(void) { int num_1=100,num_2=1; cout<<"before function call "<<endl; cout<<"num_1="<<num_1<<endl; cout<<"num_2="<<num_2<<endl; swap(&num_1,&num_2); cout<<endl; cout<<"after function call "<<endl; cout<<"num_1="<<num_1<<endl; cout<<"num_2="<<num_2<<endl; } void swap(int *a,int *b) { int temp; temp=*a; *a=*b; *b=temp; } 執行結果: before function call num_1=100 num_2=1 after function call num_1=1 num_2=100 Call By Address ( 傳址呼叫 )

38 Copyright © 2002 Pearson Education, Inc. Slide 38 #include using namespace std; void swap(int &,int &); void main(void) { int num_1=100,num_2=1; cout<<"before function call "<<endl; cout<<"num_1="<<num_1<<endl; cout<<"num_2="<<num_2<<endl; swap(num_1,num_2); cout<<endl; cout<<"after function call "<<endl; cout<<"num_1="<<num_1<<endl; cout<<"num_2="<<num_2<<endl; } void swap(int &a,int &b) { int temp; temp=a; a=b; b=temp; } 執行結果: before function call num_1=100 num_2=1 after function call num_1=1 num_2=100 Call By Reference ( 傳參考呼叫 )

39 Copyright © 2002 Pearson Education, Inc. Slide 39 使用 call by address( 傳址呼叫 ) 的時機 當函數傳回值不止一個時,透過傳址呼叫, 可以讓函數多一個將資料傳回主程式的途徑 將陣列傳入函數 將字串傳入函數 傳遞物件變數的指標

40 Copyright © 2002 Pearson Education, Inc. Slide 40 傳值、傳址、傳參考的比較 傳值呼叫傳址呼叫傳參考呼叫 原型宣告 void swap(int,int);void swap(int *,int *);void swap(int &,int &); 函數呼叫 swap(num_1,num_2);swap(&num_1,&num_2);swap(num_1,num_2); 函數宣告 void swap(int a,int b)void swap(int *a,int *b)void swap(int &a,int &b) 參數是 否改變 否是是

41 Copyright © 2002 Pearson Education, Inc. Slide 41 #include using namespace std; double sum_matrix(double [],int); int main(void) { int size=4; double matrix[4]; srand(time(NULL)); for(int i=0;i<4;i++) { matrix[i]=rand()%10; cout<<"matrix["<<i<<"]="<<matrix[i]<<endl; } cout<<"sum of matrix[0] to matrix[3] is "<<sum_matrix(matrix,size)<<endl; return 0; } double sum_matrix(double a[],int size) { double sum=0; for(int i=0;i<size;i++) { sum=sum+a[i]; } return sum; } 將陣列傳入函數 ( 一 )

42 Copyright © 2002 Pearson Education, Inc. Slide 42 #include using namespace std; double sum_matrix(double *,int); int main(void) { int size=4; double matrix[4]; srand(time(NULL)); for(int i=0;i<4;i++) { matrix[i]=rand()%10; cout<<"matrix["<<i<<"]="<<matrix[i]<<endl; } cout<<"sum of matrix[0] to matrix[3] is "<<sum_matrix(matrix,size)<<endl; return 0; } double sum_matrix(double *a,int size) { double sum=0; for(int i=0;i<size;i++) { sum=sum+a[i]; } return sum; } 將陣列傳入函數 ( 二 ) 傳址呼叫

43 Copyright © 2002 Pearson Education, Inc. Slide 43 #include using namespace std; void print_string(char *); void main(void) { char str[]="HAPPy NEW yEAR ~!!"; print_string(str); } void print_string(char *str) { while(*str!='\0') { if(*str=='y'){*str='Y';} cout<<*str; str++; } cout<<endl; } 將字串傳入函數 指標向 後移動 若小寫 y, 換為大寫 Y 傳址呼叫

44 Copyright © 2002 Pearson Education, Inc. Slide 44 AAA(i,j) void AAA(int v1,int v2) { int temp=v2; v2=v1+3; v1=temp -3; } i=1,j=2 1 v1 1 i 複製 2 v2 2 j 複製 3 2 temp -2

45 Copyright © 2002 Pearson Education, Inc. Slide 45 pAAA(&i,&j) void pAAA(int *v1,int *v2) { int temp=*v2; *v2=*v1+2; *v1=temp -2; } i=1,j=2 1 i 指標值 i 的記億體位置 v1 指向 2 j 指標值 j 的記億體位置 v2 指向 2 temp 3 0

46 Copyright © 2002 Pearson Education, Inc. Slide 46 rAAA(i, j) void rAAA(int &v1,int &v2) { int temp=v2; v2=v1+4; v1=temp -4; } i=0,j=3 i v1 j v2 3 temp 304

47 Copyright © 2002 Pearson Education, Inc. Slide 47 作業 3 發牌程式 __ 練習使用二維陣列 宣告陣列 int deal[4][13],string card[4][13] 陣列 deal[4][13] 裡存 0~51 的值 陣列 card[4][13] 裡存 string 字串,印出牌型 和點數

48 Copyright © 2002 Pearson Education, Inc. Slide 48 deal[i][j] 陣列意義: i  代表第幾 i+1 位玩家 j  代表玩家中的第 j+1 張牌 deal[0][0]  代表第 1 位玩家中的第 1 張牌 deal[2][10]  代表第 3 位玩家中的第 11 張牌

49 Copyright © 2002 Pearson Education, Inc. Slide 49 deal[i][j] 陣列意義: deal[i][j] 陣列值的意義 deal[i][j]=1… ♠ 1 deal[i][j]=14… ♥ 1 deal[i][j]=2… ♠ 2 deal[i][j]=15… ♥ 2 deal[i][j]=3… ♠ 3 deal[i][j]=16… ♥ 3 deal[i][j]=4… ♠ 4 deal[i][j]=17… ♥ 4 deal[i][j]=12… ♠ 12 deal[i][j]=25… ♥ 12 deal[i][j]= 0… ♠ 13 deal[i][j]=13… ♥ 13 ……

50 Copyright © 2002 Pearson Education, Inc. Slide 50 deal[i][j] 陣列意義: deal[i][j] 陣列值的意義 deal[i][j]=27… ♦ 1 deal[i][j]=40… ♣ 1 deal[i][j]=28… ♦ 2 deal[i][j]=41… ♣ 2 deal[i][j]=29… ♦ 3 deal[i][j]=42… ♣ 3 deal[i][j]=30… ♦ 4 deal[i][j]=43… ♣ 4 deal[i][j]=38… ♦ 12 deal[i][j]=51… ♣ 12 deal[i][j]=26… ♦ 13 deal[i][j]=39… ♣ 13 ……

51 Copyright © 2002 Pearson Education, Inc. Slide 51 deal[i][j] 陣列意義: 用 deal[i][j]%13 表示牌的點數 … deal[i][j]=27 …….deal[i][j]%13=27%13=1… ♦ 1 deal[i][j]=28 …….deal[i][j]%13=28%13=2… ♦ 2 deal[i][j]= 3 …….deal[i][j]%13= 3%13=3… ♠ 3 deal[i][j]=43 …….deal[i][j]%13=43%13=4… ♣ 13 deal[i][j]=38 ……..deal[i][j]%13=38%13=12.. ♦ 12 deal[i][j]=39 ……..deal[i][j]%13=39%13=0… ♣ 13 若 deal[i][j]%13=0… 為 13 點 …… 其他以此類推

52 Copyright © 2002 Pearson Education, Inc. Slide 52 deal[i][j] 陣列意義: 用 deal[i][j]/13 表示牌的花色 deal[i][j]/13=0…… ♠ deal[i][j]/13=1…… ♥ deal[i][j]/13=2…… ♦ deal[i][j]/13=3…… ♣ deal[i][j]= 2 …….deal[i][j]/13= 2/13=0… ♠ 1 deal[i][j]=12 …….deal[i][j]/13=12/13=0… ♠ 12 deal[i][j]=15 …….deal[i][j]/13=15/13=1… ♥ 2 deal[i][j]=24 …….deal[i][j]/13=24/13=1… ♥ 11 deal[i][j]=26 …….deal[i][j]/13=26/13=2… ♦ 13 deal[i][j]=40 ……..deal[i][j]/13=40/13=3… ♣ 3 deal[i][j]=51 ……..deal[i][j]/13=51/13=3… ♣ 12 … 其他以此類推

53 Copyright © 2002 Pearson Education, Inc. Slide 53 陣列 Card[i][j] 的意義 記錄花色和點數 deal[i][j]=1… 則 card[i][j]= ♠ 1 deal[i][j]=2… 則 card[i][j]= ♠ 2 deal[i][j]=3… 則 card[i][j]= ♠ 3 deal[i][j]=4… 則 card[i][j]= ♠ 4 deal[i][j]=12… 則 card[i][j]= ♠ 12 deal[i][j]= 0… 則 card[i][j]= ♠ 13 … 其他以此類推

54 Copyright © 2002 Pearson Education, Inc. Slide 54 需要寫的函式 void Rand(void): 將陣列 deal[4][13] 存入 0~51 不重複的亂數值 void Play(void): 將陣列 card[4][13] 存入其對應的花色和點數, 且印出每個玩家的牌型 void Pair(void): 將每個玩家的對子組合列出來

55 Copyright © 2002 Pearson Education, Inc. Slide 55 主程式部分 #include using namespace std; int deal[4][13]; string card[4][13]; void Rand(void); void Play(void); void Pair(void); int main(void) { Rand(); Play(); Pair(); return 0; } 將陣列 deal[4][13] 存 入 0~51 不重複的亂數值 印出每個玩 家的牌型 找對子

56 Copyright © 2002 Pearson Education, Inc. Slide 56 Hint 字串和數字之間的轉換: 函數 itoa :將整數轉成字串。 函數 atoi :將字串轉成整數。 函數 atof :將字串轉成 float 。 itoa(int num,char * str,10) 將 num 以 10 進位表示法轉成字串,輸入到 str

57 Copyright © 2002 Pearson Education, Inc. Slide 57 Functions Calling Functions  We’re already doing this!  main() IS a function!  Only requirement:  Function’s declaration must appear first  Function’s definition typically elsewhere  After main()’s definition  Or in separate file  Common for functions to call many other functions  Function can even call itself  ‘Recursion’

58 Copyright © 2002 Pearson Education, Inc. Slide 58 main(): ‘Special’  Recall: main() IS a function  ‘Special’ in that:  One and only one function called main() will exist in a program  Who calls main()?  Operating system  Tradition holds it should have return statement  Value returned to ‘caller’  Here: operating system  Should return ‘int’ or ‘void’

59 Copyright © 2002 Pearson Education, Inc. Slide 59 main 主程式的傳入參數 傳入 main 主程式參數的語法 Int main(int argc,char* argv[],char *env[]) argc :型態為 int ,將指出傳入 main 之參數個數。 argv :型態為字串指標陣列,所指向之字串, 為傳入主程式之字串參數。 env :型態為字串指標陣列,陣列元素所指向的 字串,為程式執行之環境參數。

60 Copyright © 2002 Pearson Education, Inc. Slide 60 main 主程式的傳入參數 argv[0] :將指向存放執行程式的名稱 與儲存路徑。 argc :為 argv 的元素個數,也就是參數的總個 數加 1 。 ( 因為 argv[0] 指向程式檔名和路徑,所以從 argv[1] 開始才正式存傳入參數 )

61 Copyright © 2002 Pearson Education, Inc. Slide 61 遞迴函數 (Recursive) #include using namespace std; int recursive_sum(int num); int loop_sum(int num); int main(void) { cout<<"Recursive: The sume from 1 to 5 is "<<recursive_sum(5)<<endl; return 0; } int recursive_sum(int value) { if(value==1) return 1; else { return recursive_sum(value-1)+value; } Value=5 Recursive_sum(4)+5 Value=4 Recursive_sum(3)+4 共呼叫 5 次 Value=3 Recursive_sum(2)+3 當 value==1 共回傳 5 次

62 Copyright © 2002 Pearson Education, Inc. Slide 62 連續加法 F(2)=1+2 F(3)=1+2+3=F(2)+3 F(4)=1+2+3+4=F(3)+4 F(5)=1+2+3+4+5=F(4)+5 int recursive_sum(int value) { if(value==1) return 1; else { return recursive_sum(value-1)+value; }

63 Copyright © 2002 Pearson Education, Inc. Slide 63 遞迴函數 (Recursive) recursive_sum(5) 5+ recursive_sum(4) 4+recursive_sum(3) 3+recursive_sum(2) 2+ recursive_sum(1) 1 第一次呼叫 第二次呼叫 第三次呼叫 第四次呼叫 第五次呼叫 2+1=3 3+3=6 4+6=10 5+10=15 傳回 main()

64 Copyright © 2002 Pearson Education, Inc. Slide 64 階層 1!=1 2!=1*2 3!=1*2*3=(2!)*3 4!=1*2*3*4=(3!)*4 5!=1*2*3*4*5=(4!)*5 int rec_muti(int value) { if(value==1) return 1; else return rec_muti(value-1)*value; }

65 Copyright © 2002 Pearson Education, Inc. Slide 65 Overloading( 重載函數 )  Same function name  Different parameter lists  Two separate function definitions  Function ‘signature’  Function name & parameter list  Must be ‘unique’ for each function definition  Allows same task performed on different data

66 Copyright © 2002 Pearson Education, Inc. Slide 66 #include using namespace std; int sum(int,int); int sum(int [],int); int main(void) { int num[5]={1,2,3,4,5}; int size=5; cout<<" 100 + 200 ="<<sum(100,200)<<endl; cout<<"1+2+3+4+5="<<sum(num,5)<<endl; return 0; } int sum(int num_1,int num_2) { int ans; ans=num_1+num_2; return ans; } int sum(int num[],int size) { int ans=0; for(int i=0;i<size;i++) ans=ans+num[i]; return ans; } 函數名稱相同 傳入型態不同 傳入型態為 int,int 傳入型態為 int [],int

67 Copyright © 2002 Pearson Education, Inc. Slide 67 Overloading Example: Average  Function computes average of 2 numbers: double average(double n1, double n2) { return ((n1 + n2) / 2.0); }  Now compute average of 3 numbers: double average(double n1, double n2, double n3) { return ((n1 + n2+n3) / 3.0); }  Same name, two functions

68 Copyright © 2002 Pearson Education, Inc. Slide 68 Overloaded Average() Cont’d  Which function gets called?  Depends on function call itself:  avg = average(10, 20);  Calls ‘two-parameter average()’  avg = average(10, 20, 30);  Calls ‘three-parameter average()’  Compiler resolves invocation based on signature of function call  ‘Matches’ call with appropriate function  Each considered separate function

69 Copyright © 2002 Pearson Education, Inc. Slide 69 Overloading Pitfall  Only overload ‘same-task’ functions  A mpg() function should always perform same task, in all overloads  Otherwise, unpredictable results  C++ function call resolution:  1 st : looks for exact signature  2 nd : looks for ‘compatible’ signature

70 Copyright © 2002 Pearson Education, Inc. Slide 70 Overloading Resolution  1 st : Exact Match  Looks for exact signature  Where no argument conversion required  2 nd : Compatible Match  Looks for ‘compatible’ signature where automatic type conversion is possible:  1 st with promotion (e.g.: int  double)  No loss of data  2 nd with demotion (e.g.: double  int)  Possible loss of data

71 Copyright © 2002 Pearson Education, Inc. Slide 71 #include using namespace std; string TYPE(double); string TYPE(int); string TYPE(char); int main(void) { cout<<" 傳入型態為 "<<TYPE(1.0)<<endl; cout<<" 傳入型態為 "<<TYPE(2)<<endl; cout<<" 傳入型態為 "<<TYPE('2')<<endl; return 0; } string TYPE(double value_1) { string TYPE="Double"; return TYPE; } string TYPE(int value_1) { string TYPE="Integer"; return TYPE; } string TYPE(char value_1) { string TYPE="Char"; return TYPE; }

72 Copyright © 2002 Pearson Education, Inc. Slide 72 Overloading Resolution Example  Given following functions:  1. void f(int n, double m); 2. void f(double n, int m); 3. void f(int n, int m);  These calls: f(98, 99);  Calls #3 f(5.3, 4);  Calls #2 f(4.3, 5.2);  Calls ???  Avoid such confusing overloading

73 Copyright © 2002 Pearson Education, Inc. Slide 73 Automatic Type Conversion and Overloading  Numeric formal parameters typically made ‘double’ type  Allows for ‘any’ numeric type  Any ‘subordinate’ data automatically promoted  int  double  float  double  char  double*More on this later!  Avoids overloading for different numeric types

74 Copyright © 2002 Pearson Education, Inc. Slide 74 Automatic Type Conversion and Overloading Example  double mpg(double miles, double gallons) { return (miles/gallons); }  Example function calls:  mpgComputed = mpg(5, 20);  Converts 5 & 20 to doubles, then passes  mpgComputed = mpg(5.8, 20.2);  No conversion necessary  mpgComputed = mpg(5, 2.4);  Converts 5 to 5.0, then passes values to function


Download ppt "Copyright © 2002 Pearson Education, Inc. Slide 1."

Similar presentations


Ads by Google