gpt4 book ai didi

c - 阶乘函数只能数到 12

转载 作者:行者123 更新时间:2023-12-02 02:39:06 24 4
gpt4 key购买 nike

对于 13 及以上,该阶乘函数开始给出错误的结果。我不知道为什么。

#include <stdio.h>

int fatorial (int p);

int main() {
int x = 13;
int test = fatorial(x);
printf("%d", test);
}

int fatorial (int p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}

对于 x = 0, 1, 2 ...12,它打印正确的结果,但是对于 13!它打印 1932053504 这是不正确的。例如,对于 x=20,它会打印 -210213273。

我知道这不是进行阶乘的最佳方法。不过,这是我的作业,它必须是这样的。

最佳答案

如果您尝试此操作,您将获得最大值 int可容纳:

#include <stdio.h>
#include <limits.h>
int main(void)
{
printf("%d\n", INT_MAX);
}

您的代码导致溢出。

如果您使用更大的类型,您可能会得到更多的数字,但不会太多。你可以使用这个:

unsigned long long fatorial (unsigned long long p) {
if (p <= 0)
return 1;
else
return p*fatorial(p-1);
}

但这不会让你走得太远。如果您想要更大的整数,则需要找到更大整数的库或创建一些自定义解决方案。此类库之一是 https://gmplib.org/但这可能超出了你的作业范围。

顺便说一句,类似 p <= 0 的条件不好。它表示负数的阶乘始终为 1,这是错误的。

关于c - 阶乘函数只能数到 12,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63904071/

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