gpt4 book ai didi

c - 递归阶乘实现的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:11 25 4
gpt4 key购买 nike

现在我正在练习在 Linux 上使用 Vim。我做了一个像这样的简单代码

#include <stdio.h>

int factorial(int n){
if (n<0) { return 0; }
else if (n==0) { return 1; }
else { return n * factorial(n); }
}

int main(void){
int n = 0;

printf("Put n value : ");
scanf("%d", &n); /* non-OP inserted ";" to help people focus on the problem */

printf("%d! = %d\n", n, factorial(n));

return 0;
}

当我输入 -1 和 0 时,它起作用了。他们返回 0 和 1。但是,当我将正整数值放在 n 上时,它不起作用。我试图找出原因,所以我使用了 gdb,
但它只是这样说:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400620 in factorial ()

我的代码有什么问题?我什至无法理解这一点。

最佳答案

n > 0 时,您的递归程序永远不会终止。 n 的值永远不会递减,因此它会继续递归运行,直到内存耗尽。

应该是return n * factorial(n-1);

关于c - 递归阶乘实现的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50207589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com