C语言_递归示例

#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函数放在前面和后面的效果相反。
自我调用前的代码都会跑,而后面的代码,会在函数开始逐步回归后再逐步调用。
有助于理解递归。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值