-
慕妹3242003
删除这些面额后,您需要处理其余部分。获得余数的最简单方法是模运算符,就像这样......int dollar = 161;int twenties = dollar / 20;int remainder = dollar % 20;int tens = remainder / 10;remainder = remainder % 10;int fives = remainder / 5;remainder = remainder % 5;int ones = remainder;上述方法不修改原始金额。通过将其重构为一个方法,它可以更容易地重用不同的面额:public int RemoveDenomination(int denomination, ref int amount){ int howMany = amount / denomination; amount = amount % denomination; return howMany;}...您可以像这样使用...int dollar = 161;int hundreds = RemoveDenomination(100, ref dollar);int fifties = RemoveDenomination(50, ref dollar);int twenties = RemoveDenomination(20, ref dollar);int tens = RemoveDenomination(10, ref dollar);int fives = RemoveDenomination(5, ref dollar);int ones = dollar;这种方法确实修改了dollar值。因此,如果您不想更改它,请将其复制到另一个变量中,然后处理该副本。
-
HUWWW
您必须使用余数并减去,直到余数变为0;int amount = 161, temp = 0;int[] denomination = { 20, 10, 5, 1 }; // you can use enums also for // readbilityint[] count = new int[denomination.Length];while (amount > 0){ count[temp] = amount / denomination[temp]; amount -= count[temp] * denomination[temp]; temp ++;}
-
湖上湖
另一种选择是使用 linq:int[] denominations = new [] { 20, 10, 5, 1 };List<int> result = denominations .Aggregate(new { Result = new List<int>(), Remainder = 161 }, (a, x) => { a.Result.Add(a.Remainder / x); return new { a.Result, Remainder = a.Remainder % x }; }) .Result;这将返回一个包含值的列表{ 8, 0, 0, 1 }。或者,您可以这样做:public static Dictionary<string, int> Denominations(int amount){ var denominations = new Dictionary<string, int>(); denominations["twenties"] = amount / 20; amount = amount % 20; denominations["tens"] = amount / 10; amount = amount % 10; denominations["fives"] = amount / 5; amount = amount % 5; denominations["ones"] = amount; return denominations;}