C 中的双精度 - 打印 50 位有效数字会产生不准确的值
我正在为我的微积分课做一个黎曼求和的积分程序。我决定在计算积分时使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
浮点的基础知识:
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.如果您需要
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.