【发布时间】:2018-11-03 13:06:00
【问题描述】:
根据我对C的了解,在下面的代码中,函数fact中的第一个return语句应该被执行。而是执行 function 中的最后一个 return 语句。代码在这里如何工作?为什么函数fact 中的第一个return 语句没有执行?
数字的阶乘:
#include <stdio.h>
int a = 2, count = 1, fact0 = 1;
int fact(int n) {
if (n == count) {
return fact0;//Only this return statement should be executed
}
fact0 = fact0 * a;
a++;
count++;
fact(n);
return 1;//But this return statement is executed , Why?
}
int main() {
int n;
setbuf(stdout, NULL);
printf("Enter the factorial number\n");
scanf("%d", &n);
printf("The factorial of the number is %d", fact(n));
return 0;
}
输出是:
Enter the factorial number
4
The factorial of the number is 1
【问题讨论】:
-
欢迎来到 Stack Overflow。请阅读the help pages、the SO tour、阅读how to ask good questions,以及this question checklist。请了解如何创建Minimal, Complete, and Verifiable Example。最后,请不要在你展示的代码中使用行号,这让我们很难复制代码自己尝试。
-
确定我会删除行号并阅读您发送的所有指南。
-
至于你的问题我建议你learn how to debug your programs。一些rubber duck debugging 以及在调试器中逐行单步执行代码应该会很快地向您显示问题。
-
您的问题的问题是您希望它从第一次返回中返回,但您没有解释为什么您有这种期望 - 因为对我们来说这似乎很明显。
-
@Allan :不,你不正确。但是,对您的问题的任何澄清都应该通过编辑问题来添加,而不是添加很少有人会阅读的评论。在递归调用之前,count 会递增,递归调用将返回并调用第二个 return 语句。第一个 return 将被调用一次(至少是第一次从
main()调用),之后递归展开。在递归中,您必须有一个不会进一步递归的“最内层”返回。