2010-04-12 50 views
3

我試圖讓這個程序將用戶定義的美元數量分解成最少的賬單。我不認爲我的for循環正在運行,因爲如果我把一個writeline線放在它們中,當它運行時它不會顯示出來。在c中分解貨幣#

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication13 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      Console.Write("Enter the amount of money: $"); 
      int totalAmount = Convert.ToInt32(Console.ReadLine()); 
      calculateNumberOfBills(totalAmount); 
     } 

     static void calculateNumberOfBills(int totalAmount) 
     { 

      int[] denominations = { 20, 10, 5, 1 }; 
      int[] numberOfBills = new int[4]; 
      for (numberOfBills[0] = 0; totalAmount < 20; numberOfBills[0]++) 
      { 
       totalAmount = totalAmount - 20; 
      } 
      for (numberOfBills[1] = 0; totalAmount < 10; numberOfBills[1]++) 
      { 
       totalAmount = totalAmount - 10; 
      } 
      for (numberOfBills[2] = 0; totalAmount < 5; numberOfBills[2]++) 
      { 
       totalAmount = totalAmount - 5; 
      } 
      for (numberOfBills[3] = 0; totalAmount <= 0; numberOfBills[3]++) 
      { 
       totalAmount = totalAmount - 1; 
      } 
      Console.WriteLine("Number of twenties" + numberOfBills[0]); 
      Console.WriteLine("Number of tens" + numberOfBills[1]); 
      Console.WriteLine("Number of fives" + numberOfBills[2]); 
      Console.WriteLine("Number of ones" + numberOfBills[3]); 
     } 
    } 
} 
+0

什麼是您使用您的測試的總金額? – 2010-04-12 06:51:39

回答

2

看看這個:

for (numberOfBills[0] = 0; totalAmount >= 20; numberOfBills[0]++) 
    { 
     totalAmount = totalAmount - 20; 
    } 
    for (numberOfBills[1] = 0; totalAmount >= 10; numberOfBills[1]++) 
    { 
     totalAmount = totalAmount - 10; 
    } 
    for (numberOfBills[2] = 0; totalAmount >= 5; numberOfBills[2]++) 
    { 
     totalAmount = totalAmount - 5; 
    } 
    for (numberOfBills[3] = 0; totalAmount > 0; numberOfBills[3]++) 
    { 
     totalAmount = totalAmount - 1; 
    } 
+0

確定工作,但我不得不改變最後一個循環到totalAmount >= 1;謝謝。你能告訴我爲什麼它不以另一種方式工作嗎? – Covertpyro 2010-04-12 06:56:24

+0

哇,現在想起來似乎很明顯,猜測這就是我在編程時得到的,當我很累的時候。 – Covertpyro 2010-04-12 07:02:30

0

在你的「for」循環,你有逆條件=>總金額< 20意味着它執行循環,而總金額爲 20 - 這與你想要的相反。

將其更改爲

for(...;totalAmount > 20; ...) 
2

這是一個家庭作業的問題,對不對?

 for (numberOfBills[0] = 0; totalAmount < 20; numberOfBills[0]++) 

使其

 for (numberOfBills[0] = 0; totalAmount >= 20; numberOfBills[0]++) 

,然後再試一次:) 中心件是在環路應該運行的條件。

1

對不起,在這一點上這是「不是一個真正的問題」,應該最有可能被標記爲家庭作業。

您的「小於」比較應該更改爲「大於」比較,您很樂意使用您的解決方案。現在發生的事情是一個整數溢出,最終導致你的第一個for循環,這是循環無限循環,直到然後打破。

有更簡單的方法來解決您的問題,嘗試用一個單一的循環和模運算符)。

+0

+1對於模運算符。它的使用並不經常。 :-) – Patrick 2010-04-12 07:28:12

0

試試這個,有點不太代碼

int amt = 73; 

    Dictionary<int, int> dic = new Dictionary<int, int>() {{20,0},{10,0},{5,0},{1,0}}; 
    int[] keys =new int[dic.Count]; 
    dic.Keys.CopyTo(keys, 0); 

    foreach (int i in keys) 
    {    
     if (amt >= i) 
     { 
      dic[i] = amt/i; 
      amt = amt % i; 
     } 
    }