我正在为我的微积分类(class)使用黎曼求和进行积分程序。我决定在计算积分时使用 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 位?
感谢您的帮助。
最佳答案
浮点基础知识:
http://en.wikipedia.org/wiki/Floating_point
您的情况的答案0.10
不能完全用二进制浮点表示。因此,它只能精确到 16 位左右。然而您正试图将其打印到小数点后 50 位。
关于c - C 中的 double - 打印 50 位有效数字会产生不准确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21101987/