Function

Why Functions?

  • 減少重複編寫同樣的程式碼
  • 編寫程式時邏輯更流暢
  • 增加程式的可讀性
  • 使 debug 更容易

Function in math

Function in programming

f(x)=2x+3
g(x)=x+3y
  • 命名:函式的名字
  • 參數:丟進去的參數
  • 定義:函式要做的事
  • 呼叫:叫函式執行

f

x

2x+3

5

1

Function in C++

int func(int a, int b){
	return a+b;
}
型態 名稱(參數1型態 參數1名稱, 參數2型態 參數2名稱...){
    要做的事;
    return 回傳的東西;
    //return: 結束並回傳數值
}
  • 函數的型態是回傳值的型態決定
  • 參數都要打型態,中間用逗號隔開

Example 1

#include <iostream>
using namespace std;

int max(int a, int b){
    if(a>b){
    	return a;
    }
    else{
    	return b;
    }
}

int main(){
    int p=1;
    int r=2;
    cout<<max(p,r);
    return 0;
}

Example 2

void print_name(string name){
    cout<<"Hello "<<name<<"!";
}
int main(){
    string YourName;
    cin>>YourName;
    print_name(YourName);
	return 0;
}

void :空。

只能作為 Return Type,不能作為變數的型別,return 可省略。

Practice 1

做一個可以交換兩個整數數的函數。

a

a

b

b

Resources

C++好用的函式庫

cppreference

cplusplus

稍微介紹常用的函式吧~

(下學期會介紹更多呦~)

sort

#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int a[10]={1,3,6,2,6,8,39,0,-4,555};
    sort(a,a+5);
    for(int i=0;i<10;i++){
        cout<<a[i]<<" ";
    }
    cout<<'\n';
    sort(a+3,a+10);
    for(int i=0;i<10;i++){
        cout<<a[i]<<" ";
    }
    return 0;
}
//1 2 3 6 6 8 39 0 -4 555
//1 2 3 -4 0 6 6 8 39 555

Recursion

Recursion in math

Recursion in programming

F_1=1 \\ F_2=1 \\ F_n=F_{n-1}+F_{n-2}
int f(int n){
    if(n==1||n==2){
    	return 1;
    }
    else{
    	return f(n-1)+f(n-2);
    }
}

Recursion?

  • 把大問題轉換成小問題
  • 在函式中呼叫自己
  • 定義終止條件
  • 將小問題的解組合成大問題

Applications

  • 費氏數列
  • 階乘
  • 最大公因數
  • 帕斯卡三角形
  • 河內塔

Practice 1_factorial

把下面的程式碼補上來計算階乘吧!

int Factorial(int n){
    if(n==1){
    	return 1;
    }
    else{
    	//這裡應該return什麼
    }
}

可以在main函式裡呼叫他,測試效果喔

Practice 1_factorial

Factorial(3)

=3 * Factorial(2)

=3*(2*Factorial(1))

=3*2*1

Factorial(3)

3 * Factorial(2)

2 * Factorial(1)

1

Practice 2

greatest common divisor

這次的任務是做一個最大公因數的函式,

我們先來複習一下輾轉相除法~

34

10

3

30

4

2

8

2

2

4

0

Practice 2

greatest common divisor

int gcd(int a, int b){
    if(b==0){
    	//return _____ ;
    }
    else{
    	//return _____ ;
    }
}

Practice_2_ans

int gcd(int a, int b){
	if(b==0){
    	return a ;
    }
    else{
    	return gcd(b, a%b) ;
    }
}
Made with Slides.com