gpt4 book ai didi

c - 如何增加C中整数的范围?

转载 作者:行者123 更新时间:2023-11-30 21:10:47 24 4
gpt4 key购买 nike

我尝试解决 SPOJ 上的小阶乘问题,但得到“错误答案”。我编写了以下代码:

#include <stdio.h>

int main() {

int t,i, num;
unsigned long long int fact=1;

scanf ("%d", &t);

while (t-- >0) {

fact=1;

scanf ("%d", &num);

for (i=num; i>0; i--) {
fact*=i;
}
printf ("%llu\n",fact);
}

return 0;
}

此代码无法计算 100 这样的大输入的阶乘。需要进行哪些更改?

最佳答案

在 C 和 C++ 中,最大允许范围为 -2^63+1 到 +2^63-1,这是针对 long long 数据类型的。正如您所看到的,这个范围仍然太小,无法存储 >20 位数字。您必须使用 char 数组来存储每个数组索引的单个数字。在 C++ 中执行此操作的一种方法:

#include<stdio.h>
#include<iostream>
int main()
{
int t;
char a[200]; //array will have the capacity to store 200 digits.
int n,i,j,temp,m,x;

scanf("%d",&t); //enter total elements
while(t--)
{
scanf("%d",&n); // enter no. one at a time
a[0]=1; //initializes array with only 1 digit, the digit 1.
m=1; // initializes digit counter

temp = 0; //Initializes carry variable to 0.
for(i=1;i<=n;i++)
{
for(j=0;j<m;j++)
{

x = a[j]*i+temp; //x contains the digit by digit product
a[j]=x%10; //Contains the digit to store at position j
temp = x/10; //Contains the carry value that will be stored on later indeces
}
while(temp>0) //while loop that will store the carry value on array.
{
a[m]=temp%10;
temp = temp/10;
m++; // increments digit counter
}
}
for(i=m-1;i>=0;i--)
printf("%d",a[i]);
printf("\n");
}
return 0;
}

关于c - 如何增加C中整数的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27753381/

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