【发布时间】:2021-02-09 19:00:37
【问题描述】:
编辑:一个可能的解决方案: 我试图打印剩余的,我得到了这个: 3.75 1.75 0.75 0.25 0.049999997 0.029999997 0.009999998
0.04 和 0.02 我猜是问题所在!
我的问题:
我必须用java写一个收银机程序——我做的收银机只有以下注释:
- 一法郎:0.01
- 两法郎:0.02
- 五法郎:0.05
- 十法郎:0.10
- 二十法郎:.20
- 五十法郎:0.50
- 一生丁:1
- 两生丁:2
- 五生丁:5
- 十生丁:10
- 二十生丁:20
- 五十生丁:50
例如:
输入:
price = 11.25
cash = 20
输出:
Five Francs, Two Francs, One Franc, Fifty Centimes, Twenty Centimes, Five Centimes
我的问题是我的代码给了我这个输出:
Five Francs, Teo Francs, One Franc, Fifty Centimes, Twenty Centimes, Two Centimes, Two Centimes
请注意,我如何得到 2 of 2 centtimes 而不是 5 centtimes 所以我矮了 1 生丁。
我使用一个简单的循环和枚举解决了它:
我的枚举:
public enum bill {
Fifty_Francs( 50.00f),
Twenty_Francs( 20.00f),
Ten_Francs( 10.00f),
Five_Francs( 5.00f),
Teo_Francs( 2.00f),
One_Franc( 1.00f),
Fifty_Centimes( 0.50f),
Twenty_Centimes( 0.20f),
Ten_Centimes( 0.10f),
Five_Centimes( 0.05f),
Two_Centimes( 0.02f),
One_Centime( 0.01f);
private final float value;
private final String description;
bill(float value) {
this.value = value;
this.description = " " + this.name().replace("_", " ");
}
public float getValue() {
return this.value;
}
@Override
public String toString() {
return this.description;
}
}
我的打印功能:
public static void getGhange(double price, double cash) {
if (cash < price){
System.out.println("Wrong buddy");
} else if (cash == price) {
System.out.println("Nothing");
} else { //CH > PP
float remaining = (float) (cash - price);
StringBuilder change = new StringBuilder();
for (bill d : bill.values()) {
while (remaining >= d.getValue()) {
remaining -= d.getValue();
change.append(d).append(',');
}
}
change.setLength(change.length() - 1); // remove , at the end
System.out.println(change.toString().trim());
}
}
【问题讨论】:
-
我在猜测,但我猜这是浮动问题,对吧??
-
查看stackoverflow.com/questions/27598078/… 的已接受答案,它特别提到了钱,cmets 对此进行了很好的讨论。