C 中的双精度 - 打印 50 位有效数字会产生不准确的值

发布于 2024-12-10 19:38:27 字数 414 浏览 4 评论 0原文

我正在为我的微积分课做一个黎曼求和的积分程序。我决定在计算积分时使用 C,并且我注意到我的程序中存在由这个问题引起的巨大错误。

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

int main(int argc, char** argv) {

double x = 2.0/20.0;
printf("%1.50f \n", x);


return (EXIT_SUCCESS);
}    

该程序给了我:0.10000000000000000555111512312578270211815834045410。我的问题:为什么会发生这种情况?我该如何解决这个问题?或者至少四舍五入到小数点后 15 位?

感谢您的帮助。

I'm doing an integration program with Riemann sums for my Calculus class. I've decided to use C when computing my integrals, and I noticed a huge error in my program that derives from this problem.

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

int main(int argc, char** argv) {

double x = 2.0/20.0;
printf("%1.50f \n", x);


return (EXIT_SUCCESS);
}    

The program gives me : 0.10000000000000000555111512312578270211815834045410. My question: Why does this happen? And how can I fix this? Or at least round off to ~15 decimal places?

Thanks for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吻泪 2024-12-17 19:38:27

浮点的基础知识:

http://en.wikipedia.org/wiki/Floating_point

在您的情况下,答案 0.10 不能完全用二进制浮点表示。因此,它只能精确到 16 位左右。然而您正试图将其打印到小数点后 50 位。

The basics of floating-point:

http://en.wikipedia.org/wiki/Floating_point

The answer in your case 0.10 is not exactly representable in binary floating-point. Therefore, it's only accurate to about 16 digits. Yet you are trying to print it out to 50 decimal places.

生活了然无味 2024-12-17 19:38:27

如果您需要 double 可以提供的更准确的结果,那么您可能需要查看一些 可用的任意精度库

If you need more accurate results that what double can offer, then you may want to check out some of the arbitrary precision libraries that are available.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文