将硬币数量转换为四分之一、一角硬币、五分硬币、便士的递归函数
Recursive function to convert coin amount into quarters, dimes, nickles, pennies
我有一个小项目,可以将一定数量的硬币转换成各自的四分之一、一角硬币、五分硬币、便士金额。基本思路是这样的:
public static void coinCombo() {
int amount = getInt();
int quarter_cnt = amount/QUARTER;
int r1 = amount%QUARTER;
int dime_cnt = r1/DIME;
int r2 = r1%DIME;
int nickel_cnt = r2/NICKEL;
int r3 = r2%NICKEL;
System.out.println("Quarters: " + quarter_cnt);
System.out.println("Dimes: " + dime_cnt);
System.out.println("Nickels: " + nickel_cnt);
System.out.println("Pennies: " + r3);
}
但是,这对我来说看起来相当笨重。我想知道如何递归执行此操作。我看到我使用上一个操作的剩余部分来获取下一个操作。我觉得这可以做得更简洁。有人可以提供一个递归方式的例子吗?
我会这样做。
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);
版画
Quarters: 4
Dimes: 1
Nickels: 1
Pennies: 4
请注意,可以轻松修改以上内容以包含更大面额的钞票(</code>、<code>
和 </code> 钞票)。</p>
<p>但这是您的递归解决方案。它需要一个参数。</p>
<pre><code>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);
}
}
我有一个小项目,可以将一定数量的硬币转换成各自的四分之一、一角硬币、五分硬币、便士金额。基本思路是这样的:
public static void coinCombo() {
int amount = getInt();
int quarter_cnt = amount/QUARTER;
int r1 = amount%QUARTER;
int dime_cnt = r1/DIME;
int r2 = r1%DIME;
int nickel_cnt = r2/NICKEL;
int r3 = r2%NICKEL;
System.out.println("Quarters: " + quarter_cnt);
System.out.println("Dimes: " + dime_cnt);
System.out.println("Nickels: " + nickel_cnt);
System.out.println("Pennies: " + r3);
}
但是,这对我来说看起来相当笨重。我想知道如何递归执行此操作。我看到我使用上一个操作的剩余部分来获取下一个操作。我觉得这可以做得更简洁。有人可以提供一个递归方式的例子吗?
我会这样做。
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);
版画
Quarters: 4
Dimes: 1
Nickels: 1
Pennies: 4
请注意,可以轻松修改以上内容以包含更大面额的钞票(</code>、<code>
和 </code> 钞票)。</p>
<p>但这是您的递归解决方案。它需要一个参数。</p>
<pre><code>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);
}
}