2016-11-25 69 views
0

你好我有這個代碼的問題我有種邏輯,但仍然不完整,即時假設計算出最少數量的硬幣交付在1便士和500便士之間換錢。當我使用500不打印任何XX什麼即時通訊做錯了,只有當我進入工作1以上500任何幫助將感激找出要交付的硬幣的最小數量

public class exchange{ 
    public static void main(String[] args) 
    { 
     int coin; 
     int OnePound = 0; 
     int TwoPound = 0; 
     int FiftyP = 0; 
     int TwentyP = 0; 
     int TenP = 0; 
     int FiveP = 0; 
     int TwoP = 0; 
     int OneP = 0; 

     int Compare = 0; 
     int Tcoins = 0 ; 

     System.out.print("#Introduce the amount of Coins"); 
     coin = BIO.getInt(); 

     if (coin < 1 || coin > 500) 
     { 
     System.out.print("Invalid amount "+coin+"p"); 
     } 

     if (coin == 1) 
     { 
      System.out.println("1 coin"); 
      System.exit(1); 
     } 

     while (Compare != coin) 
     { 

      if (200 <= coin && Compare < coin) 
      { 
       Compare = Compare + 200; 
       TwoPound = TwoPound + 1; 
       Tcoins = Tcoins + 1; 
      } 

      if (100 <= coin && Compare < coin) 
      { 
       Compare = Compare + 100; 
       OnePound = OnePound + 1; 
       Tcoins = Tcoins + 1; 
      } 

      if (50 <= coin && Compare < coin) 
      { 
       Compare = Compare + 50; 
       FiftyP = FiftyP + 1; 
       Tcoins = Tcoins + 1; 
      } 

      if (20 <= coin && Compare < coin) 
      { 
       Compare = Compare + 20; 
       TwentyP = TwentyP + 1; 
       Tcoins = Tcoins + 1; 
      } 

      if (10 <= coin && Compare < coin) 
      { 
       Compare = Compare + 10; 
       TenP = TenP + 1; 
       Tcoins = Tcoins + 1; 
      } 

      if (5 <= coin && Compare < coin) 
      { 
       Compare = Compare + 5; 
       FiveP = FiveP + 1; 
       Tcoins = Tcoins + 1; 
      } 

      if (2 <= coin && Compare < coin) 
      { 
       Compare = Compare + 2; 
       TwoP = TwoP + 1; 
       Tcoins = Tcoins + 1; 
      } 

      if (1 <= coin && Compare < coin) 
      { 
       Compare = Compare + 1; 
       OneP = OneP + 1; 
       Tcoins = Tcoins + 1; 
      } 

     } 

     System.out.print("Amount of coins: "+Tcoins); 

    } 
} 
+1

這種事情在這個和其他網站上被問過很多次嗎? –

回答

0

你要測試你的運行總和,總的區別:

 if (200 <= coin - Compare) 
     { 
      Compare = Compare + 200; 
      TwoPound = TwoPound + 1; 
      Tcoins = Tcoins + 1; 
     } 
     else if (100 <= coin - Compare) 
     { 
      Compare = Compare + 100; 
      OnePound = OnePound + 1; 
      Tcoins = Tcoins + 1; 
     } 

ALSO一切必須else if因爲你想嘗試大的值,直到不再有大的值將適合,然後嘗試較小。

+0

即時通訊仍然混淆,硬幣是一個值用戶介紹...所以最終不應該匹配? 編輯:nvm我現在明白了。 – Pankake

+0

但是,如果我這樣做,硬幣和比較將永遠不會匹配:C,並且永遠不會退出循環x.x – Pankake

+0

因此,第一個必須是If和其他7個ifs應該是其他嗎? – Pankake