C 带递归的阶乘程序
嗨,我在阶乘程序中做了一些检查,我很困惑27,40,50是如何进入输出的,ans是10C 带递归的阶乘程序,c,C,嗨,我在阶乘程序中做了一些检查,我很困惑27,40,50是如何进入输出的,ans是10 #include<stdio.h> int fact(int n) { if(n==1) { printf("hello1 %d\n",n); return 1; } else { printf("hello2 %d\n",n); n*=fact(n-1); printf("hello3 %d\n",n); } // printf("hello4 %d\n",n);
#include<stdio.h>
int fact(int n)
{
if(n==1)
{
printf("hello1 %d\n",n);
return 1;
}
else
{
printf("hello2 %d\n",n);
n*=fact(n-1);
printf("hello3 %d\n",n);
}
// printf("hello4 %d\n",n);
}
void main()
{
int n,s;
printf("Enter no. ");
scanf("%d",&n);
s=fact(n);
printf("\n%d",s);
printf("%c",10);
}
在
else
块中放置return
语句
else
{
printf("hello2 %d\n",n);
n *= fact(n-1);
printf("hello3 %d\n",n);
return n;
}
我觉得奇怪的是,
fact()
中的else
块中没有return
,它应该是:
else
{
printf("hello2 %d\n",n);
n*=fact(n-1);
printf("hello3 %d\n",n);
return n;
}
我发现有趣的是,在反向遍历过程中,它是如何拾取27
#include<stdio.h>
int fact(int n)
{
if(n==1)
{
printf("hello1 %d\n",n);
return 1;
}
else
{
printf("hello2 %d\n",n);
// return n*=fact(n-1);
n*=fact(n-1);
// printf("hello3 %d\n",n);
// return n;
}
// printf("hello4 %d\n",n);
}
void main()
{
int n,s;
printf("Enter no. ");
scanf("%d",&n);
s=fact(n);
printf("\n%d",s);
printf("%c",10);
}
#包括
整数事实(整数n)
{
如果(n==1)
{
printf(“hello1%d\n”,n);
返回1;
}
其他的
{
printf(“hello2%d\n”,n);
//返回n*=事实(n-1);
n*=事实(n-1);
//printf(“hello3%d\n”,n);
//返回n;
}
//printf(“hello4%d\n”,n);
}
void main()
{
int n,s;
printf(“输入编号”);
scanf(“%d”和“&n”);
s=事实(n);
printf(“\n%d”,s);
printf(“%c”,10);
}
如果我注释//printf(hello3),它会给出结果。如果
n,你的函数不会返回
任何内容=1
,请打开并阅读编译器的警告。提示:使用printf(“第%d行n=%d\n”,第n行)代码>;另外,使用所有警告和调试信息(gcc-Wall-Wextra-g
)编译并使用调试器(gdb
)您的代码显示未定义的行为。。。问题中相同的未定义行为@BasileStarynkevitch;True:)不应编译。在返回n
后添加分号。
#include<stdio.h>
int fact(int n)
{
if(n==1)
{
printf("hello1 %d\n",n);
return 1;
}
else
{
printf("hello2 %d\n",n);
// return n*=fact(n-1);
n*=fact(n-1);
// printf("hello3 %d\n",n);
// return n;
}
// printf("hello4 %d\n",n);
}
void main()
{
int n,s;
printf("Enter no. ");
scanf("%d",&n);
s=fact(n);
printf("\n%d",s);
printf("%c",10);
}