gpt4 book ai didi

c - C中的数字精度错误

转载 作者:太空狗 更新时间:2023-10-29 14:59:24 26 4
gpt4 key购买 nike

这是我写的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
double num;
int tmp;
printf("enter a number!\n");
scanf("%lf",&num);
tmp=num*10000;
printf(" temp=%d\n",tmp);

return 0;
}

当我输入数字 1441.1441 时,我得到的结果是 14411440 而不是14411441 这显然是我输入的数字乘以 10000 后的正确结果。有人可以帮我解决这个问题吗?

最佳答案

由于绝大多数实数实际上无法准确表示,您可能会发现 1441.1441 实际上存储为类似 1441.14409999_blah_blah_blah 的内容。你可以通过插入找到:

printf ("%.50lf\n", num);

紧接着 scanf 并查看(删除尾随零):

1441.14409999999998035491444170475006103515625

现在这实际上是基于您输入的正确(即最接近)值。从那里下一个最高的数字给你:

1441.144100000000207728589884936809539794921875

第一个值的错误是:

0.00000000000001964508555829524993896484375
^ ~ 2 x 10^-14

而第二个错误是:

0.000000000000207728589884936809539794921875
^ ~ 2 x 10^-13

你可以看到后者的误差大约是后者的 10 倍。

当您将其乘以 10000 并尝试将其硬塞进 int 时,它会向下 舍入(截断)。这是因为 (C11) 标准在 6.3.1.4 中是这样说的:

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero).

您可以尝试的一件事是将鞋拔线改成:

tmp = num * 10000 + 0.5;

这有效地将截断转换为舍入操作。我认为这将适用于所有情况,但您可能想要测试它(并密切关注它)以防万一。

关于c - C中的数字精度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13525376/

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