对递归一直是很敬畏的,绕不过弯来,这次参考了网上写的代码,再根据自己的理解写的递归。欢迎各位指教。![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)
运行结果:
代码(用c写的):
#include "stdio.h"
int judgenum();
int sum(int b);
int main(){
int number;
int resu=-1;
printf("********递归累加******\n");
printf("请输入一个大于0的数:\n");
scanf("%d",&number);
if(number<=0){
resu=judgenum();
}else{
resu=number;
}
printf("%d\n",resu);
printf("累加结果是:%ld\n",sum(resu));
return 0;
}
int judgenum(){
printf("请输入一个大于0的数:\n");
int a;
scanf("%d",&a);
printf("判断是否大于0这里输出的:%d\n",a);
if(a<=0){
return judgenum();
}else{
return a;
}
}
int sum(int b){
int result=1;
if(b==1){
return result;
}else{
return sum(b-1)+b;
}
}