递归 入门

递归 入门

最好的入门方式,还是为了解决实际问题,引入新的方法。

本文以乘法实现为例

输入:

2 3

输出:

6

//方法一:用*运算符
#include <stdio.h>
int main(){
    int a,b,c;
    scanf("%d%d",&a,&b);
    c=a*b;
    printf("%d",c);
    return 0;

}

//方法二:采用+的循环运算方式
#include <stdio.h>
int main(){
    int a,b,c=0,i,t;
    scanf("%d%d",&a,&b);
    if(a<b){//目标 a>=b
        t=a;
        a=b;
        b=t;
    }
    //循环次数以较小次数为好
    for(i=1;i<=b;i++)
        c+=a;
    printf("%d",c);
    return 0;
}
//方法四:递归 感觉写得很棒,深得递归的精髓
#include <stdio.h>
int a,b,c;
int mul(int a,int b){
    if(b==1)//结束条件
        return a;
    return mul(a,b-1)+a;
}
int main(){
    int t;
    scanf("%d%d",&a,&b);
    if(a<b){//目的 a>=b
        t=a;
        a=b;
        b=t;
    }
    c=mul(a,b);
    printf("%d",c);
    return 0;
}


//方法三:递归 感觉写得不太好
#include <stdio.h>
int a,b,c=0;
int mul(int step){//step代表递归执行步骤
    if(step==b+1)//递归结束条件
        return c;
    c+=a;
    return mul(step+1);
}
int main(){
    int t;
    scanf("%d%d",&a,&b);
    if(a<b){//目的 a>=b
        t=a;
        a=b;
        b=t;
    }
    mul(1);
    printf("%d",c);
    return 0;
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值