Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

java - Recursive function to convert coin amount into quarters, dimes, nickles, pennies


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...