函式&遞迴

林芊妘

函式

奶油乳酪:250g

 細砂糖:60g

雞蛋:2顆

動物性鮮奶油:120ml

低筋麵粉:10g

香草精:少許

鹽:少許

食材+步驟

函式是什麼

用C++寫的話

#include <iostream>
using namespace std;

int recipe(int egg, int sugar, int cheese)
{
    int finish=egg+sugar+cheese;
    return finish;
}

int main()
{
    int a, b, c;
    cin>>a>>b>>c;
    cout<<recipe(a, b, c)<<endl;
    return 0;
}

 宣告 函式名稱(型別+參數)

 {

     參數處理

     回傳值

 }

副程式

 型別 變數

 輸入變數

 變數丟入函式中

 輸出

主程式

*參數要分別宣告

用C++寫的話

#include <iostream>
using namespace std;

int recipe(int egg, int sugar, int cheese)
{
    int finish=egg+sugar+cheese;
    return finish;
}

int main()
{
    int a, b, c;
    cin>>a>>b>>c;
    int recipe=recipe(a,b,c);
    cout<<recipe<<endl;
    return 0;
}

*主程式中的變數名稱不能使用函式名稱!

觀念題

#include <iostream>
using namespace std;

int compare(int A, int B)
{
    int result;
    if(A>B) result=A%3;
    else if(A==B) result=A/3+B/2;
    else result=B*B;
    return result;
}

int main()
{
    int a, b;
    cin>>a>>b;
    int num=compare(a,b);
    cout<<num<<endl;
    return 0;
}

輸入 a=25,b=23

輸出 num=1

輸入 a=50,b=80

輸出 num=6400

輸入 a=18,b=18

輸出 num=15

輸入 a=21,b=21

輸出 num=17

不放參數

#include <iostream>
using namespace std;
int f1()
{
    return 1;
}   

float f2()
{
    return 3.8;
}
int main()
{
    int n=f1();
    float m=f1()+f2();
    cout<<n<<" "<<m;
    return 0;
}

1 4.8

void函式

(不需回傳值return)

#include <iostream>
using namespace std;
void hello()
{
    cout<<"hi"<<endl;
}
int main()
{
    hello();
    return 0;
}

hi

#include <iostream>
using namespace std;
void hello();
/*有這個函式 
實際上要做什麼在後面自己找*/

int main ()
{
    hello();       
}
    
void hello()
{                  
    cout<<"hi"<<endl;
}

hi

void函式

(給定預設值)

#include <iostream>
using namespace std;

void PRank(int i=1)
{
   cout<<"Phoebe's rank is "<<i<<endl;
}
    
int main ()
{
    PRank();
    PRank(2);    
}

Phoebe’s rank is 1

Phoebe’s rank is 2

遞迴

函示自己呼叫自己=>遞迴

遞迴是什麼

須設定終止條件! 讓它不會無限下去

需執行重複動作時使用

#include <iostream>
using namespace std;

int f(int a)
{
    if(a==0)
        return 1;
    else if(a==1)
        return 1;
    else
        return a*f(a-1);
}

int main()
{
    int x;
    cin>>x;
    cout<<f(x);
    return 0;
}

費氏數列

0!=1

1!=1

n!=n*(n-1)!

觀念題

#include <iostream>
using namespace std;

int f(int A, int B){
    int C, times=0;
    if(times>20){
        return A;
    }
    if(A>B){
        C=A%20-B*2;
        return f(C,B);
        times++;    
    }
    else return A;
}

int main(){
    int a,b;
    cin>>a>>b;
    cout<<f(a,b);
}

輸入 a=3,b=5

輸出 3

輸入 a=7,b=2

輸出 -1

輸入 a=355,b=10

輸出 -5

輸入 a=54,b=3

輸出 num=2

寫題囉~

#include <bits/stdc++.h>
using namespace std;

int f(int n)
{
    int sum=0;
    if(n<10)
    {
        return n; 
    }
    
    while(n>0){
        sum=sum+(n%10);
        n=n/10;
    } 
    return f(sum);
}

int main()
{
    int a;
    
    while(cin>>a && a!=0)
    {
        cout<<f(a)<<endl;
    }
    
    return 0;
}

函式&遞迴

By chainy

函式&遞迴

  • 101