我有示例代码
double k=3.14, l=0.5, m=1.3333;
System.out.println(k+":"+k%1);
System.out.println(l+":"+l%1);
System.out.println(m+":"+m%1);
输出结果:
3.14:0.14000000000000012
0.5:0.5
1.3333:0.33329999999999993
为什么会这样呢?我期望 x%1 返回 x 值的非整数部分?
最佳答案
参见Is floating point math broken?
Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented.
关于Java 模数 1 (%1) 返回近似值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40542804/