猿问

在c#中制作公式以将美元金额转换为面额

我正在制作一个程序,将任何输入金额转换为二十、十、五和一的面额。这是我遇到的问题:


int twenties = dollar/20;

int tens = twenties/2;

int fives = tens/2;

int ones = fives/5;

美元是输入金额,二十多岁的表达似乎是唯一正确的。例如:我输入 161,结果 161 等于 8 个 20、4 个 10、2 个 5 和 0 个。但它应该会出现,因为 161 等于 8 个 20、0 个 10、0 个 5 和 1 个。我知道对此有一个非常简单的答案,但我就是不明白,谢谢大家。


繁星淼淼
浏览 188回答 3
3回答

慕妹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 =&nbsp; &nbsp; denominations&nbsp; &nbsp; &nbsp; &nbsp; .Aggregate(new { Result = new List<int>(), Remainder = 161 }, (a, x) =>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a.Result.Add(a.Remainder / x);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new { a.Result, Remainder = a.Remainder % x };&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; .Result;这将返回一个包含值的列表{ 8, 0, 0, 1 }。或者,您可以这样做:public static Dictionary<string, int> Denominations(int amount){&nbsp; &nbsp; var denominations = new Dictionary<string, int>();&nbsp; &nbsp; denominations["twenties"] = amount / 20;&nbsp; &nbsp; amount = amount % 20;&nbsp; &nbsp; denominations["tens"] = amount / 10;&nbsp; &nbsp; amount = amount % 10;&nbsp; &nbsp; denominations["fives"] = amount / 5;&nbsp; &nbsp; amount = amount % 5;&nbsp; &nbsp; denominations["ones"] = amount;&nbsp; &nbsp; return denominations;}
随时随地看视频慕课网APP
我要回答