递归 入门
最好的入门方式,还是为了解决实际问题,引入新的方法。
本文以乘法实现为例
输入:
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;
}