【发布时间】:2012-01-27 12:07:35
【问题描述】:
可能重复:
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 数量将等于 6.66 。但在第二次计算之后,金额将是 1.6600000000000001 。我不明白为什么从 double 中减去 int 会导致这样的结果。
【问题讨论】:
-
它被称为floating-point arithmetic,这个问题在SO上不断地被问到。阅读:csharpindepth.com/Articles/General/FloatingPoint.aspx
-
获得直接问题的答案后,如果您需要更高的精度,您可能希望在代码中使用 BigDecimal 类。