Java 模数 1 (%1) 返回近似值

标签 java modulus

我有示例代码

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/

相关文章:

java - 如何将 JPanel 转换为文件?

algorithm - 有人可以解释一下这段代码中模数的使用吗?

c++ - 对二进制字符串进行范围查询?

c++ - 当操作数之一为负值时的模运算c++

java - 表没有映射?

java - 罗马数字转整数

java - 如何将 JAR 文件添加到现有的 gradle 项目?

java - 如何在 JTextArea 上添加 JScrollPane

python - 为什么 (0.0006*100000)%10 是 10

C++ -当检查输入是否为整数时,循环不断重复 -