【发布时间】:2014-01-27 20:19:17
【问题描述】:
我目前正在为学校做一个作业,我需要编写一个程序,它需要在这种模式下返回你的更改
输入: 购买金额:$12.45 给定金额:$15.00
输出: 零钱:2.55 美元 2张一美元的钞票 2个季度 1 镍
但是,如果我处理这种情况,它工作得很好。现在,如果我想让这个场景发挥作用,我会得到 p>
输入: 购买金额:$19.51 给定金额:$50.01
输出:
二十美元钞票 1 十元钞票:1 宿舍:1 硬币:2 便士:4
这是不正确的,因为我要返回客户 30.49 而不是 30.5
不知道这里有什么问题。
谢谢
boolean isFiveBillOn = false, isTwentybillOn = false, isTenbillOn = false, isDollarOn = false, isQuartersOn = false, isDimesOn = false, isNicklesOn = false, isPenniesOn = false;
//retrieve amount due
String moneyd = JOptionPane.showInputDialog("Enter the amount due");
double amountd = Double.parseDouble(moneyd);
String moneyr = JOptionPane.showInputDialog("Enter amount you would like to pay");
double amountr = Double.parseDouble(moneyr);
//calculate difference
double difference = (amountr - amountd);
//convert to pennies
int balance = (int)(difference * 100);
//twenty dollar bill
int twentydollars = balance / 2000;
balance = (balance % 2000);
if (twentydollars > 0) {
isTwentybillOn = true;
}
//ten dollar bill
int tendollars = balance / 1000;
balance = (balance % 1000);
if (tendollars > 0) {
isTenbillOn = true;
}
//five dollar bill
int fivedollars = balance / 500;
balance = (balance % 500);
if (fivedollars > 0) {
isFiveBillOn = true;
}
//dollar bill
int dollars = balance / 100;
balance = (balance % 100);
if (dollars > 0) {
isDollarOn = true;
}
//quartes
int quarters = balance / 25;
balance = (balance % 25);
if (quarters > 0) {
isQuartersOn = true;
}
//dimes
int dimes = balance / 10;
balance = (balance % 10);
if (dimes > 0) {
isDimesOn = true;
}
//nickles
int nickles = balance / 5;
balance = (balance % 5);
if (nickles > 0){
isNicklesOn = true;
}
//pennies
int pennies = balance / 1;
balance = (balance % 1);
if (pennies > 0){
isPenniesOn = true;
}
//checking for difference over 0
if (difference < 0) {
JOptionPane.showMessageDialog(null, "The amount received can't be less than the amount owned");
} else {
// Returning Message
} if (isTwentybillOn) {
System.out.println("Twenty dollar bill " + twentydollars);
} if (isTenbillOn) {
System.out.println("Ten dollar bill: " + tendollars);
} if (isDollarOn) {
System.out.println("One Dollar Bill: " + dollars);
} if (isQuartersOn) {
System.out.println("Quarters: " + quarters);
} if (isDimesOn) {
System.out.println("Dimes: " + dimes);
} if (isNicklesOn) {
System.out.println("Nickles: " + nickles);
} if (isPenniesOn) {
System.out.println("Pennies: " + pennies);
} else {
System.out.println("Thanks! have a good day");
}
}
【问题讨论】:
-
不要用
double代表金钱。使用BigDecimal或其他一些确切的数据类型。 -
@Keppil - 你能解释一下为什么吗?
-
因为浮点数不能表示任意实数。它始终只是一个近似值
-
是的,一般来说,您永远不应该使用浮点数/双精度数来表示金钱(除非您正在做股票市场分析并且不需要精确到一分钱的结果)。至于为什么,您已经在上面证明了这一点。