【发布时间】:2016-04-15 02:17:41
【问题描述】:
我想制作一个小系统,可以为我返回任何价值的优化数量的纸币和硬币。
这是我的代码:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
double amount = Double.parseDouble(br.readLine());
if (amount > 0 && amount < 1000000.00) {
// ############################# BILLS ############################
double rest100 = amount / 100;
double rest50 = amount % 100;
double rest20 = rest50 % 50;
double rest10 = rest20 % 20;
double rest5 = rest10 % 10;
double rest2 = rest5 % 5;
// ############################ COINS ############################
double rest01 = rest2 % 2;
double rest050 = rest01 % 1;
double rest025 = rest050 % .5;
double rest010 = rest025 % 25;
double rest005 = rest010 % .1;
double rest001 = rest005 % .05;
System.out.println("BILLS:\n"
+ (int) rest100
+ " bill(s) of 100.00\n"
+ (int) rest50 / 50
+ " bill(s) of 50.00\n"
+ (int) rest20 / 20
+ " bill(s) of 20.00\n"
+ (int) rest10 / 10
+ " bill(s) of 10.00\n"
+ (int) rest5 / 5
+ " bill(s) of 5.00\n"
+ (int) rest2 / 2
+ " bill(s) of 2.00\n"
+ "COINS:\n"
+ (int) (rest01 / 1)
+ " coin(s) of 1.00\n"
+ (int) (rest050 / .5)
+ " coin(s) of 0.50\n"
+ (int) (rest025 / .25)
+ " coin(s) of 0.25\n"
+ (int) (rest010 / .1)
+ " coin(s) of 0.10\n"
+ (int) (rest005 / .05)
+ " coin(s) of 0.05\n"
+ (int) (rest001 / .01)
+ " coin(s) of 0.01");
}
}
嗯,这几乎是正确的,钞票运作良好,我的问题是硬币。
这里有一些输入:
- 576.73 // 打印正确
- 8.45 // 打印不正确
- 9.45 //打印不正确,看下面:
实际输出:
BILLS:
0 bill(s) of 100.00
0 bill(s) of 50.00
0 bill(s) of 20.00
0 bill(s) of 10.00
1 bill(s) of 5.00
2 bill(s) of 2.00
COINS:
0 coin(s) of 1.00
0 coin(s) of 0.50
1 coin(s) of 0.25
4 coin(s) of 0.10
0 coin(s) of 0.05
4 coin(s) of 0.01
预期输出:
BILLS:
0 bill(s) of 100.00
0 bill(s) of 50.00
0 bill(s) of 20.00
0 bill(s) of 10.00
1 bill(s) of 5.00
2 bill(s) of 2.00
COINS:
0 coin(s) of 1.00
0 coin(s) of 0.50
1 coin(s) of 0.25
2 coin(s) of 0.10
0 coin(s) of 0.05
0 coin(s) of 0.01
PS:我不会发布所有预期的输出,因为它会让问题比现在更大,但是如果您需要,我可以发布。提前致谢。
【问题讨论】:
-
我怀疑问题出在 0.1、0.05 和 0.01 上,因为它们不能精确地表示为浮点数。考虑使用整数来解决这类问题,因为整数运算既精确又快速。
-
你为什么使用 math.floor(rest100): ?为什么你有一个 50 美分的硬币?
-
@kpie 真的一无所获.. 一个错误,但没关系(不幸的是)。我的国家有 50 美分硬币。
-
请为我们这些忙于运行您的代码的人发布一个无效输出的示例。
-
更正此行
double rest010 = rest025 % .25;(0.25 前缺少小数点)。此外,使用 double 进行模运算(%运算符)可能会因为不精确而产生错误的结果(例如,8.45 打印4 coin(s) of 0.01)。
标签: java coin-change