我在使用此代码时遇到了困难。当我输入95.95作为购买价格和100作为支付价格时,我不断得到一个舍入错误,例如它返回4美元,4便士而不是4美元和5便士。所有其他值都可以正常工作,但由于某种原因,当小数位为.95或.05时,它很难返回正确的便士......
public static void main(String[] args){
//Read price per pack
Scanner in = new Scanner(System.in);
System.out.println("Enter purchase price: ");
double purchasePrice = in.nextDouble();
System.out.println("Enter amount paid: ");
double amountPaid = in.nextDouble();
//Compute change due
if (amountPaid < purchasePrice)
{System.out.printf("Error, you need more money!");
}
else {
int diff = (int)(( amountPaid - purchasePrice)*100);
int dollars = diff/100;
diff = diff%100;
int quarters = diff/25;
diff = diff%25;
int dimes = diff/10;
diff = diff%10;
int nickels = diff/5;
diff = diff%5;
int pennies = diff/1;
diff = diff%1;
System.out.println("--------------------");
System.out.println("Total Change due: " + (amountPaid - purchasePrice));
System.out.println("--------------------");
System.out.println("Dollars: " + dollars);
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
}
答案 0 :(得分:1)
你的问题就在这一行
int diff = (int)(( amountPaid - purchasePrice)*100);
您将向下的数量向下舍入到下一个int
以下价格的100倍。由于double
并不一定要精确地表示十进制数,因此可能存在浮点错误,当您进行乘法时,该错误会被放大100倍。该产品可能略高于或低于整数分数,因此您的舍入可以导致金额向下舍入,几乎整整一分。
您实际想要做的是将分数的double
值舍入最接近的 int
,而不是下面的int
。您可以在回合前添加0.5来做到这一点。
int diff = (int)(( amountPaid - purchasePrice)*100 + 0.5);
一般来说,如果你想用它做精确的计算,你绝不应该使用double
存储一笔钱。我建议学习使用BigDecimal
类,其中像这样的问题就会消失。