我正在尝试创建一个输入量的程序,并将它们分成多少硬币。到目前为止,我所写的内容大部分时间都给了我正确的金额,但有时它会是一分钱,我不知道为什么。
public static void main(String[] args) {
double amount;
System.out.println("This program will display the number of "
+ "quarters, dimes, nickels and pennies based on the "
+ "amount you enter below.");
System.out.println();
System.out.print("Please enter an amount: ");
Scanner scan = new Scanner(System.in);
amount = scan.nextDouble();
double quarter = amount/0.25;
amount = amount % 0.25;
double dime = amount/0.10;
amount = amount % 0.10;
double nickel = amount/0.05;
amount = amount % 0.05;
double penny = amount/0.01;
System.out.println("Quarters: " + (int)quarter);
System.out.println("Dimes " + (int)dime);
System.out.println("Nickels " + (int)nickel);
System.out.println("Pennies " + (int)penny);
当我输入2.47时,我得到:
Please enter an amount: 2.47
Quarters: 9
Dimes: 2
Nickels: 0
Pennies: 2
但是当我输入1.47时,我得到:
Please enter an amount: 1.47
Quarters: 5
Dimes: 2
Nickels: 0
Pennies: 1
答案 0 :(得分:0)
问题的最可能原因是浮点运算会出现舍入误差。在某个时刻,其中一个中间浮点结果并不完全准确,当您使用强制转换将double
转换为int
时,错误已放大。
要详细解释为何会发生此类事情,请阅读Is floating point math broken?
的答案解决方案您应该使用int
(或long
)类型重新编码,以表示整数美分。
从这开始:
long amount = (long) (100 * scan.nextDouble());
然后相应地重新编码方法的其余部分。