【发布时间】:2021-10-28 16:58:30
【问题描述】:
出于某种原因,每当我输入一个大于 12 的数字时,它 = 0。
这是我的代码(我尝试过使用 long int 但它只是用随机数代替):
#include <stdio.h>
int main()
{
{
int c, n, f = 1;
printf("Enter a number to calculate its factorial\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
f = f * c;
if (n < 0)
printf("Cannot calculate the factorial of a negative number\n");
else
{
printf("Factorial of %d = %d\n", n, f);
}
}
【问题讨论】:
-
对产品使用
unsigned long long。这最多可以让您使用格式说明符%llu报告 20!。或者使用double获取近似结果,或者使用大整数库。 -
关于“我尝试过使用 long int”。如果
long在您的系统上是 64 位(在我的系统上是 32 位),请使用格式说明符%lu。 -
一个好的 bigint 库是 GMP:gmplib.org
-
您可以使用具有适当变量类型的查找表。
-
可以使用string。缓慢,但没有真正的上限。不需要特殊的库。