Possible Duplicate:
Floating point arithmetic not producing exact results in Java
Floating point inaccuracy examples
在Java中,给出以下代码:
double amount = scan.nextDouble();
tenBills = (int)amount / (int)10;
amount = amount - (tenBills * 10);
fiveBills = (int)amount / (int)5;
amount = amount - (fiveBills * 5);
第一次计算后,假设输入 16 amount 将等于 6.66 。但第二次计算后金额将为 1.6600000000000001 。我不明白为什么从 double 中减去 int 会导致这样的结果。
最佳答案
如果你想要硬核解释,请阅读经典What Every Computer Scientist Should Know About Floating-Point Arithmetic 。它解释了为什么浮点运算中不可避免地存在微小的舍入误差,就像您所看到的那样。
如果您只想要一个摘要:计算机以二进制表示一切。在某些情况下,进行浮点运算时的二进制表示会导致微小的不准确。
关于java - 双减 int 给出意想不到的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8627774/