Function – 遞迴



Function – 遞迴

0 0


csdc-2016


On Github alechuang98 / csdc-2016

\( \newcommand{\ord}[1]{\mathcal{O}\left(#1\right)} \newcommand{\abs}[1]{\lvert #1 \rvert} \newcommand{\floor}[1]{\lfloor #1 \rfloor} \newcommand{\ceil}[1]{\lceil #1 \rceil} \newcommand{\opord}{\operatorname{\mathcal{O}}} \newcommand{\fail}{\operatorname{\mathcal{F}}} \newcommand{\flk}{\operatorname{\mathfrak{F}}} \newcommand{\suf}{\operatorname{\sigma}} \newcommand{\rank}{\operatorname{\mathcal{R}}} \newcommand{\sa}{\operatorname{\mathcal{SA}}} \newcommand{\hei}{\operatorname{\mathcal{H}}} \newcommand{\edps}{\operatorname{\mathcal{E}}} \newcommand{\mx}{\operatorname{\mathcal{M}}} \newcommand{\argmax}{\operatorname{arg\,max}} \newcommand{\cons}[1]{\left[ \: #1 \: \right]} \newcommand{\str}[1]{\texttt{"#1"}} \)

Function

alechuang98

自訂函式

int f(int x){
    return 3*x*x-2*x+1;
    //f(x)=3x^2-2x+1
}

為什麼要用函式呢

  • 方便
  • 容易維護
  • 遞迴(等等教)

宣告與定義

type function_name(type1 x,type2 y){
    ..
    code
    ..
    return value;
}
以Hello world 為例
void output(){
    printf("Hello world\n");
    return;
}

int main(){
    //call
    output();
}

遞迴

遞迴的定義

  • 如果不懂遞迴的定義,請參見遞迴的定義

遞迴的例子其實很多

  • 藍綠互噴
  • 教學叫你去問網管 網管叫你去問教學
  • ...

void what_is_recursive(int understand_recursive){
    if(understand_recursive==1)return;
    what_is_resurcive(understand_recursive);
}

Ex. 費氏數列

int fibonacci(int a){
  if(!a)return 0;
  if(a==1)return 1;
  return fibonacci(a-1)+fibonacci(a-2);
}
int main(){
  int n;
  scanf("%d",&n);
  printf("%d\n",fibonacci(n));
}

Practice

  • SMJ #1033
  • Green Judge #b022
  • Green Judge #b023
Functionalechuang98