Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 带递归的阶乘程序_C - Fatal编程技术网

C 带递归的阶乘程序

C 带递归的阶乘程序,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);

嗨,我在阶乘程序中做了一些检查,我很困惑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);
}
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);
}