I would just do it like this.
static final int[] den = {25,10,5,1};
static final String[] names = {"Quarters", "Dimes","Nickels", "Pennies"};
public static void coinCombo(int amount) {
for (int i = 0; i < den.length; i++) {
System.out.printf("%s: %d%n", names[i], amount/den[i]);
amount %= den[i];
}
}
coinCombo(119);
Prints
Quarters: 4
Dimes: 1
Nickels: 1
Pennies: 4
Note that the above could easily be modified to include larger denominations ($10
, $5
, and $1
bills).
But here is your recursive solution. It requires one more argument.
coinCombo(232,0);
public static void coinCombo(int amount, int i) {
if (amount > 0) {
System.out.printf("%s: %d%n", names[i], amount/den[i]);
coinCombo(amount % den[i], i+1);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…