我正在为我的中学课程用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。为什么会这样呢?