当我执行这个程序时,我遇到了段错误,但不知道为什么。 只要它大于 0,它就应该返回输入的阶乘(?)。
#include <stdio.h>
int factorial(int input)
{
if (input > 0)
{
return input * factorial(input--);
}
else
{
return 1;
}
}
int main()
{
printf("%d", factorial(23));
return 0;
}
最佳答案
factorial(input--)
并没有像你想象的那样做。使用阶乘(input-1)
。
这是一个page that documents the post-decrement operator这应该有助于正确使用它。您永远不必使用它。您始终可以使用 +
、-
和 =
(赋值)执行您想要的操作。
您的程序正在产生段错误,因为正如您所编写的,factorial(23)
调用 factorial(23)
,导致 stack overflow .
关于c - 为什么执行此 C 程序时会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28010513/