为什么这段代码给出的结果不准确?
double a = 0.3 + 0.3 + 0.3;
System.out.println(a);
float b = 0.3f + 0.3f + 0.3f;
System.out.println(b);
结果是
0.8999999999999999
0.90000004
最佳答案
在 Java 中, double 值是 IEEE floating point numbers 。除非它们是 2 的幂(或 2 的幂之和,例如 1/8 + 1/4 = 3/8),否则即使它们具有高精度,也无法准确表示。某些浮点运算会加剧这些 float 中存在的舍入误差。在上述情况下,浮点错误已经变得足够严重,足以显示在输出中。
关于java - 使用 double 和 float 计算不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26831635/