您的位置:首页 > 其它

递推的几个经典例子

2013-07-17 22:09 106 查看
1、斐波那契数列

#include <stdio.h>

int fab(int n ){
if(n == 1){
return 1;
}else if(n == 2){
return 1;
}else{
return fab(n-1)+fab(n-2);
}

}
int main(){
int n ;
scanf("%d",&n);
printf("%d\n",fab(n));
}


2、hano塔

#include <stdio.h>

void hano(char from,int n ,char to,char spare){

if(n>0){
hano(from,n-1,spare,to);
printf("move %d from %c to %c\n",n,from,to);
hano(spare,n-1,to,from);
}

}

int main(){

hano('a',3,'b','c');
return 0;
}


3、输出一个数字的各位

#include <stdio.h>

void decbit(int n){
if(n>9){
decbit(n/10);
}

printf(" %d",n%10);
}
int main(){
decbit(497382);
}


以下附上递归的过程图示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: