gpt4 book ai didi

c - 如何在 C 中正确输出超过 16 位的整数?

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:41 26 4
gpt4 key购买 nike

这里的代码只给出正确的输出,直到 21 的阶乘,之后它从左边开始正确最多 16 位数字,然后剩余的数字只给出为零。我尝试将变量 c 的类型从 double 更改为 long double 但它只是给出错误或者不打印阶乘。

#include <stdio.h>

FILE *fp;
long double facto(int i);
int main() {
int n, i;
double c;
printf("enter no. to find factorial till:\n");
scanf("%d", &n);
fp = fopen("output_of_factorial.txt", "w");
fputs("Number |\t Factorial\n\n", fp);

for (i = 1; i <= n; i++) {
c = facto(i);
fprintf(fp, "%d\t|\t %.0Lf\n", i, c);
}
fclose(fp);
return 0;
}

long double facto(int x) {
if (x == 1)
return 1;
else
return x * facto(x - 1);
}

最佳答案

Tye double 只有 53 位精度,long double 在您的平台上可能有 80 位。使用浮点运算将为您提供对最高有效数字正确的近似结果。使用整数可为您提供准确的结果,但前提是它小于类型的范围。

您可以使用至少 64 位宽的 long long 类型,即 19 位数字,或者多一位,类型 unsigned long long 允许两倍大的整数:

LLONG_MAX = 9223372036854775807  //  > 9.22e19
ULLONG_MAX = 18446744073709551615 // > 1.84e20

这是代码的修改版本:

#include <stdio.h>

unsigned long long facto(int i);

int main(void) {
int n, i;
unsigned long long c;
FILE *fp;

printf("enter no. to find factorial till: ");
if (scanf("%d", &n) == 1) {
fp = fopen("output_of_factorial.txt", "w");
if (fp != NULL) {
fputs("Number | Factorial\n\n", fp);
for (i = 1; i <= n; i++) {
c = facto(i);
fprintf(fp, "%6d | %20llu\n", i, c);
}
fclose(fp);
}
}
return 0;
}

unsigned long long facto(int x) {
if (x <= 1)
return 1;
else
return x * facto(x - 1);
}

一直到 20:

Number |            Factorial

1 | 1
2 | 2
3 | 6
4 | 24
5 | 120
6 | 720
7 | 5040
8 | 40320
9 | 362880
10 | 3628800
11 | 39916800
12 | 479001600
13 | 6227020800
14 | 87178291200
15 | 1307674368000
16 | 20922789888000
17 | 355687428096000
18 | 6402373705728000
19 | 121645100408832000
20 | 2432902008176640000

但由于算术溢出,对于 21 及以上失败。

更进一步,您可以使用 128 位整数,如果它们在您的平台上可用(uint128_t__uint128__uint128_t)但是您需要编写自己的转换函数来输出十进制表示形式。

更好的方法是使用多精度(又名 bignum)包来处理非常大的数字,通常只受可用内存的限制。

关于c - 如何在 C 中正确输出超过 16 位的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41085520/

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