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

时间:2018-09-13 04:45:07

标签: c#

我正在编写一个程序,将任何输入金额转换为二十,十,五和一的面额。这是我遇到的麻烦:

.attrEntry .error.itemLevel,
.attrEntry .helpText,
.attrEntry .tiny {
  display: none!important;
}

.attrEntry .error.itemLevel.show {
  display: block!important;
}

美元是输入金额,二十年代的表达方式似乎是唯一可以正确表达的方式。例如:我输入161,结果是161等于8二十,4十,2个5和0。但是应该出来,因为161等于8二十,0十,0五和一。我知道有一个非常简单的答案,谢谢大家。

7 个答案:

答案 0 :(得分:2)

您必须使用余数并减去,直到余数变为0;

int amount = 161, temp = 0;
int[] denomination = { 20, 10, 5, 1 }; // you can use enums also for 
// readbility
int[] count = new int[denomination.Length];

while (amount > 0)
{
    count[temp] = amount / denomination[temp];
    amount -= count[temp] * denomination[temp];
    temp ++;
}

答案 1 :(得分:1)

删除这些面额后,您需要处理其余部分。最简单的方法是modulus operator,就像这样……

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的值。因此,如果您不想更改它,请在另一个变量中创建一个副本,然后在副本上进行操作。

答案 2 :(得分:1)

另一种选择是使用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;
}

答案 3 :(得分:0)

此控制台应用说明了可能的解决方案:

internal static class Program
{
    internal static void Main()
    {
        var results = GetDenominationValues();
        foreach (var result in results)
        {
            Console.WriteLine($"{result.Key} - {result.Value}");
        }

        Console.ReadLine();
    }

    private static Dictionary<int, int> GetDenominationValues()
    {
        var amount = 161;
        var denominations = new[] { 20, 10, 5, 1 };
        var results = new Dictionary<int, int>();

        foreach (var denomination in denominations)
        {
            results.Add(denomination, amount / denomination);
            amount = amount % denomination;

            if (amount == 0) break;
        }

        return results;
    }
}

关键区别在于:

amount = amount % denomination;

在随后的计算中使用前一个除法的余数。

答案 4 :(得分:-1)

如果除法大于零,则将余数传递(使用模运算符%),否则将原始值传递给行中的下一个除法。重复直到没有更多的划分。 另外,将tens除以10,fives除以5,将ones除以1。

答案 5 :(得分:-2)

请使用下面的返回字典的函数

    public static Dictionary<string, int> Denominations(int amount)
    {
        Dictionary<string, int> denominations = new Dictionary<string, int>() { { "twenties", 0 }, { "tens", 0 }, { "fives", 0 }, { "ones", 0 } };

        int twenties, tens, fives, ones;
        if (amount >= 20)
        {
            twenties = amount/20;
            denominations["twenties"] = twenties;
            amount -= twenties * 20;
        }
        if (amount >= 10)
        {
            tens = amount/10;
            denominations["tens"] = tens;
            amount -= tens * 10;
        }
        if (amount >= 5)
        {
            fives = amount/5;
            denominations["fives"] = fives;
            amount -= fives * 5;
        }

        if (amount >= 1)
        {
            ones = amount;
            denominations["ones"] = ones;

        }

        return denominations;
    }

答案 6 :(得分:-3)

您要输入密码吗?

_________________ ERROR at setup of test_myfunc[10-clean_data] _________________

self = <_pytest.python.CallSpec2 object at 0x7f8a4ff06518>, name = 'shape'

    def getparam(self, name):
        try:
>           return self.params[name]
E           KeyError: 'shape'

/usr/lib/python3.6/site-packages/_pytest/python.py:684: KeyError

During handling of the above exception, another exception occurred:

self = <SubRequest 'clean_data' for <Function 'test_myfunc[10-clean_data]'>>
fixturedef = <FixtureDef name='shape' scope='function' baseid='pytest-parametrized.py' >

    def _compute_fixture_value(self, fixturedef):
        """
            Creates a SubRequest based on "self" and calls the execute method of the given fixturedef object. This will
            force the FixtureDef object to throw away any previous results and compute a new fixture value, which
            will be stored into the FixtureDef object itself.

            :param FixtureDef fixturedef:
            """
        # prepare a subrequest object before calling fixture function
        # (latter managed by fixturedef)
        argname = fixturedef.argname
        funcitem = self._pyfuncitem
        scope = fixturedef.scope
        try:
>           param = funcitem.callspec.getparam(argname)

/usr/lib/python3.6/site-packages/_pytest/fixtures.py:484: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <_pytest.python.CallSpec2 object at 0x7f8a4ff06518>, name = 'shape'

    def getparam(self, name):
        try:
            return self.params[name]
        except KeyError:
            if self._globalparam is NOTSET:
>               raise ValueError(name)
E               ValueError: shape

/usr/lib/python3.6/site-packages/_pytest/python.py:687: ValueError

During handling of the above exception, another exception occurred:

request = <SubRequest 'data' for <Function 'test_myfunc[10-clean_data]'>>

    @pytest.fixture()
    def data(request):
        """ Get the appropriate datset based on the request """
>       return request.getfuncargvalue(request.param)

pytest-parametrized.py:55: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/usr/lib/python3.6/site-packages/_pytest/fixtures.py:439: in getfuncargvalue
    return self.getfixturevalue(argname)
/usr/lib/python3.6/site-packages/_pytest/fixtures.py:430: in getfixturevalue
    return self._get_active_fixturedef(argname).cached_result[0]
/usr/lib/python3.6/site-packages/_pytest/fixtures.py:455: in _get_active_fixturedef
    self._compute_fixture_value(fixturedef)
/usr/lib/python3.6/site-packages/_pytest/fixtures.py:526: in _compute_fixture_value
    fixturedef.execute(request=subrequest)
/usr/lib/python3.6/site-packages/_pytest/fixtures.py:778: in execute
    fixturedef = request._get_active_fixturedef(argname)
/usr/lib/python3.6/site-packages/_pytest/fixtures.py:455: in _get_active_fixturedef
    self._compute_fixture_value(fixturedef)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <SubRequest 'clean_data' for <Function 'test_myfunc[10-clean_data]'>>
fixturedef = <FixtureDef name='shape' scope='function' baseid='pytest-parametrized.py' >

    def _compute_fixture_value(self, fixturedef):
        """
            Creates a SubRequest based on "self" and calls the execute method of the given fixturedef object. This will
            force the FixtureDef object to throw away any previous results and compute a new fixture value, which
            will be stored into the FixtureDef object itself.

            :param FixtureDef fixturedef:
            """
        # prepare a subrequest object before calling fixture function
        # (latter managed by fixturedef)
        argname = fixturedef.argname
        funcitem = self._pyfuncitem
        scope = fixturedef.scope
        try:
            param = funcitem.callspec.getparam(argname)
        except (AttributeError, ValueError):
            param = NOTSET
            param_index = 0
            if fixturedef.params is not None:
                frame = inspect.stack()[3]
                frameinfo = inspect.getframeinfo(frame[0])
                source_path = frameinfo.filename
                source_lineno = frameinfo.lineno
                source_path = py.path.local(source_path)
                if source_path.relto(funcitem.config.rootdir):
                    source_path = source_path.relto(funcitem.config.rootdir)
                msg = (
                    "The requested fixture has no parameter defined for the "
                    "current test.\n\nRequested fixture '{0}' defined in:\n{1}"
                    "\n\nRequested here:\n{2}:{3}".format(
                        fixturedef.argname,
                        getlocation(fixturedef.func, funcitem.config.rootdir),
                        source_path,
                        source_lineno,
                    )
                )
>               fail(msg)
E               Failed: The requested fixture has no parameter defined for the current test.
E               
E               Requested fixture 'shape' defined in:
E               pytest-parametrized.py:27
E               
E               Requested here:
E               /usr/lib/python3.6/site-packages/_pytest/fixtures.py:526

/usr/lib/python3.6/site-packages/_pytest/fixtures.py:506: Failed