【发布时间】:2016-02-06 21:05:29
【问题描述】:
这是我必须做的:
编写一个程序,让少于一美元的金额找零。程序的输入必须是小于 100 的正整数,表示金额,以美分为单位。输出必须是原始货币数量以及可以构成该数量的一组硬币(硬币、硬币、镍币)。该程序必须产生包含产生给定数量所需的最小硬币数量的零钱。 不应包含任何便士。例如,输入 54 应产生如下结果:
54 美分需要 2 个季度,1 个镍
而不是
54 美分需要 2 个季度,0 个硬币,1 个镍
以下是我到目前为止所做的,但如果我输入 13、14、23、24、33、34 等,则不会四舍五入。
任何帮助将不胜感激。
import java.util.Scanner;
public class MakeChangetest {
public static String makeChange(int change) throws BadChangeException {
int amount;
String x = "";
if (change > 0 && change < 100) {
amount = (int) ((Math.round(change / 5)) * 5);
if (amount == 0 || amount == 100) {
x = "No change to be given.";
}
if (amount == 5) {
x = change + " cents requires " + " 1 nickel ";
} else if (amount == 10 || amount == 20) {
x = change + " cents requires " + (amount / 10) + " dimes ";
} else if (amount == 15) {
x = change + " cents requires " + (amount / 10) + " dime, "
+ " 1 nickel ";
} else if (amount == 25 || amount == 50 || amount == 75) {
x = change + " cents requires " + (amount / 25) + " quaters ";
} else if (amount == 30 || amount == 55 || amount == 80) {
x = change + " cents requires " + (amount / 25) + " quaters, "
+ " 1 nickel";
} else if (amount == 35 || amount == 60 || amount == 70 || amount == 45 || amount == 85
|| amount == 95) {
if (amount % 25 == 10) {
x = change + " cents requires " + (amount / 25) + " quater, "
+ "1 dime ";
} else
x = change + "cents requires " + (amount / 25) + " quaters, "
+ " 2 dimes ";
} else if (amount == 40 || amount == 65 || amount == 90) {
if (amount / 25 == 15) {
x = change + " cents requires " + (amount / 25) + " quater, "
+ " 1 dime, " + " 1 nickel ";
} else
x = change + " cents requires " + (amount / 25) + " quaters, "
+ " 1 dime, " + " 1 nickel ";
}
} else
throw new BadChangeException(
"Amount is not in the range to be given change for.");
return x;
}
public static void main(String[] args) throws BadChangeException {
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount to calculate the amount of change to be given:");
double t = input.nextDouble();
try {
System.out.println(makeChange((int) t));
} catch (BadChangeException ex) {
System.out.print("Amount is not in the range to be given change for.");
}
}
}
【问题讨论】: