gpt4 book ai didi

在C中计算大数的阶乘

转载 作者:太空狗 更新时间:2023-10-29 16:28:11 27 4
gpt4 key购买 nike

在我的 C 代码中,我想计算 1 到 100 范围内数字的阶乘。对于较小的数字,该函数有效,但对于较大的数字(例如 100!),它返回不正确的结果。有没有办法在 C 中处理大数的阶乘?

我使用的编译器是 gcc v4.3.3。我的代码如下:

#include <stdio.h>
#include <math.h>

double print_solution(int);

int main(void)
{
int no_of_inputs, n;
int ctr = 1;

scanf("%d",&no_of_inputs); //Read no of inputs

do
{
scanf("%d",&n); //Read the input
printf("%.0f\n", print_solution(n));
ctr++;
} while(ctr <= no_of_inputs);

return 0;
}

double print_solution(int n)
{
if(n == 0 || n == 1)
return 1;
else
return n*print_solution(n-1);
}

最佳答案

没有标准的 C 数据类型可以准确地处理大到 100 的数字!。如果使用 arbitrary precision integer arithmetic,您唯一的选择,通过图书馆或自己完成。

如果这只是一些业余爱好项目,我建议您自己尝试一下。这是一种有趣的练习。如果这与工作相关,请使用预先存在的库。

您通常会获得的最大 C 数据类型是 64 位整数。 100!是 10157 的量级,至少需要 525 位才能准确存储为整数。

关于在C中计算大数的阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1384160/

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