亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用遞歸的Java硬幣找零問題——不工作

使用遞歸的Java硬幣找零問題——不工作

莫回無 2023-09-27 16:12:46
我的程序是錯誤的,因為賺 2 英鎊的方法肯定不止 2 種。public class TwoPounds{? ? private static int[] coins = {1, 2, 5, 10, 20, 50, 100, 200};? ? private static int amount;? ? private static int count;? ? public TwoPounds()? ? {? ? ? ? amount = 2;? ? ? ? count = 0;? ? }? ? public static void main(String[] args)? ? {? ? ? ? TwoPounds run = new TwoPounds();? ? ? ? count = run.combos(amount);? ? ? ? run.printOut();? ? }? ? public int combos(int amountIn)? ? {? ? ? ?? ? ? ? if (amountIn == 0)? ? ? ? {? ? ? ? ? ? return 1;? ? ? ? }? ? ? ? if (amountIn < 0)? ? ? ? {? ? ? ? ? ? return 0;? ? ? ? }? ? ? ? int combosCount = 0;? ? ? ? for(int i = 0; i < coins.length; i++)? ? ? ? {? ? ? ? ? ? System.out.println("amountIn now is " + amountIn);? ? ? ? ? ? combosCount += combos(amountIn - coins[i]);? ? ? ? }? ? ? ? return combosCount;? ? }? ? public void printOut()? ? {? ? ? ? System.out.println("\n\n\n");? ? ? ? System.out.println("There are " + count + " ways can 2 pounds be made, "? ? ? ? ? ? + "using any number of coins");? ? ? ? System.out.println("\n\n\n");? ? }?}輸出:There are 2 ways can 2 pounds be made, using any number of coins
查看完整描述

2 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

您的coins單位是美分(或便士,因為我猜您使用的是英鎊),所以既然您使用amountIn - coins[i]它們進行表演,這意味著您的金額也是美分/便士。

因此,將您的金額更改為:

amount = 200;

值得花點時間考慮一下變量命名,以及它如何幫助識別甚至完全避免這個問題。術語“amount”和“amountIn”是不明確的。

文字中沒有任何暗示單位的內容。因此,養成使變量名稱盡可能具體且明確的習慣 - 并在適當的情況下包含單位。

例如,如果變量被稱為“amountInPounds”,那么在寫入時錯誤會變得更加明顯amountInPounds - coins[i]

現在,在更新到 之前amount = 200;,請注意:

1) 將會有大量結果(200 便士、198 便士+2p),這將需要一些時間來迭代一次一便士,加上

2)您的代碼當前編寫為遍歷每個離散的有序組合 - 例如,它將進行計數:

  • 198“1分”+1“2分”

  • 197“1分”+1“2分”+1“1分”

  • 196“1分”+1“2分”+2“1分”

  • 195“1分”+1“2分”+3“1分”等

同樣,執行時間太多了。你想要的是不要for(int i = 0; i < coins.length; i++)每次都從零開始,而是添加一個額外的參數combos- 所以像這樣:

public int combos (int amountIn, int startCoin)

{       


    // blah ... existing code ... blah


    for(int i = startCoin; i < coins.length; i++)

    {

        System.out.println("amountIn now is " + amountIn);

        combosCount += combos(amountIn - coins[i], i);

    }

最后,正如我之前所說,200 會產生很大的數字,您實際上無法確認其正確性,因此請從可以檢查的少量數字開始。


查看完整回答
反對 回復 2023-09-27
?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

該算法允許使用多個相同面額的硬幣,因此有 2 種方法可以賺 2 英鎊:

  1. {1, 1}

  2. {2}


查看完整回答
反對 回復 2023-09-27
  • 2 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號