Java 双精度值 = 0.01 更改为 0.0099999999999999787
可能的重复:
为什么不使用双倍或浮动来表示货币?
我正在为我的高中课程编写一个基本的Java命令行程序。我们现在只处理变量。它用于计算购买后零钱中任何类型的纸币和硬币的数量。这是我的程序:
class Assign2c {
public static void main(String[] args) {
double cost = 10.990;
int paid = 20;
double change = paid - cost;
int five, toonie, loonies, quarter, dime, nickel, penny;
five = (int)(change / 5.0);
change -= five * 5.0;
toonie = (int)(change / 2.0);
change -= toonie * 2.0;
loonies = (int)change;
change -= loonies;
quarter = (int)(change / 0.25);
change -= quarter * 0.25;
dime = (int)(change / 0.1);
change -= dime * 0.1;
nickel = (int)(change / 0.05);
change -= nickel * 0.05;
penny = (int)(change * 100);
change -= penny * 0.01;
System.out.println("$5 :" + five);
System.out.println("$2 :" + toonie);
System.out.println("$1 :" + loonies);
System.out.println("$0.25:" + quarter);
System.out.println("$0.10:" + dime);
System.out.println("$0.05:" + nickel);
System.out.println("$0.01:" + penny);
}
}
它应该一切都可以工作,但在最后一步,当剩下0.01美元时,便士的数量应该是1,但相反,它是0。在单步执行代码并将更改值输出到控制台几分钟后,我发现在最后一步,当 change = 0.01 时,它更改为 0.009999999999999787。为什么会发生这种情况?