首先我们用一个小程序1+2+3+4+5=15这个小程序用递归的方法求出来:
/*
目的:为了清楚的分析递归方法在执行中的顺序,应用到具体的程序当中 */ #include <stdio.h>
int s(int n);
int main(void)
{ int n = 5;
printf("结果是:%d\n",s(n));
return 0;
}
int s(int n)
{
int sum = 0;
if(n)
{ sum=s(n-1)+n; /*进入递归调用: sum=s(5)=s(4)+5; sum=s(4)=s(3)+4; sum=s(3)=s(2)+3; sum=s(2)=s(1)+2; sum=s(1)=s(0)+1; sum=s(0)=0; */ } /*输出为从后向前输出*/ printf("n = %d\t" , n); printf("sum = %d\n" ,sum);
return sum;
}
/*
用来验证递归的逆序输出,即变量在栈中是先进先出。 */
#include <stdio.h>
#include <malloc.h> void reverse(char *str); int main() { char *s; s=(char *)malloc(sizeof(char));// 一定要记得分配内存哦,不然会出现运行段错误的哦 printf("请输入一串字符:"); scanf("%s",s); reverse(s); printf("逆序后:%s\n",s); free(s);
s=NULL;
return 0;
}
void reverse(char *str) { int i=0,len=0; char c; while(str[i++]!='\0') { len++; } printf("len=%d\n",len); for(i=0;i<len/2;i++) { printf("str[%d]=%c,str[%d]=%c\n",i,str[i],len-i-1,str[len-i-1]); c=str[i]; str[i]=str[len-i-1]; str[len-i-1]=c; } // return s; } |
将一个字符串逆序输出
最新推荐文章于 2020-12-03 10:53:56 发布