#include "stdio.h"
#include "stdlib.h"
#include "math.h"
int my_fact(int x);
int my_show_bin(int x);
int main ()
{
int x = 10 , ans;
ans = my_fact(x);
printf("\n");
my_show_bin(x);
printf("\n");
printf("!%d answer is %d \n", x,ans);
system("pause");
return 0;
}
//阶乘递归
int my_fact(int x)
{
int ret = x;
if(x == 0) { //函数出口
return 1;
}else{ //函数功能
ret*=my_fact(--x);
}
}
//showbin
int my_show_bin(int x)
{
int ret = x;
if(x == 1){
printf("%d",1);
}else if(x == 0){
printf("%d",0);
}else{
ret = x % 2;
// printf("%d",ret); //这里部分的代码 会在递进的时候完成
my_show_bin(x / 2); //这里完成递归
printf("%d",ret); //递归后面的代码, 会在回归的时候完成
}
}
今天练习递归的时候发现,my_show_bin函数中,printf函数放在前面和后面的效果相反。
自我调用前的代码都会跑,而后面的代码,会在函数开始逐步回归后再逐步调用。
有助于理解递归。