逆序输出你输入的数的C程序中的递归,有一点地方不懂,请高手进:

来源:百度知道 编辑:UC知道 时间:2024/06/19 01:07:03
我问过差不多同样的问题,但这是最后一次问这样的问题:
在这个程序中,我输入4,再输入1234.
我想它是这样执行的:
1,n=4,c=getchar(1),nixu(3);
,n=3,c=getchar(2),nixu(2);
3,n=2,c=getchar(3),nixu(1);
4,n=1,c=getchar(4),nixu(0);
此时n=0,执行n<=0语句,
5,c=getch(),此时应输入“回车键”。
6,putchar(c),输出回车键,可为什么它会输出4,这个递归我哪里理解错了?
程序:
#include<stdio.h>
void nixu(int n);
void main()
{int n;
printf("the number?\n");
scanf("%d",&n);
printf("the num\n");
nixu(n);
printf("\n");
getch();
}
void nixu(int n)
{ char c;
if(n<=0)
{
c=getchar();
putchar(c);
}
else
{
c=getchar();
nixu(n-1);
putchar(c);
}
}
谢谢你的回答!
程序是对的,但我不知道我哪里把递归理解错了,我想深入了解一下递归,谢谢你的回答,但不是我想要的。

没有错,我运行了一下很正确!

递归函数的一大特征就是直接或者间接的调用自己
这是我自己写的到置输出的函数,希望能给你些些递归的启发^
void Reverse (int a[ ],int n)
{
if(n==0) return;
printf("%d,",a[n-1]);
Reverse(a,n-1)//此处调用了自身Reverse()函数。
}
main()
{
int a[]={1,2,3,4};
Reverse(a[3],4);
}