如何将钱分成单独的笔记?

时间:2017-03-03 14:30:15

标签: c# loops

我正忙着赚钱"现金补贴"程序,并试图弄清楚如何从收银机将一笔钱从最高到最低排序成单独的价值(纸币和硬币)。我真的很难想到如何以有效的方式做到这一点。 我想到的是这样的:

while (sum>=0){
   if(sum <0 R200&& sum % 200 !>0){   //R200 is the amount of 200 rand notes in the register
   sum = sum - 200.00;
   }//endif
}//endwhile

但是当我尝试这个时,我最终会因无限循环而枯萎,或者它实际上并没有减去金额

2 个答案:

答案 0 :(得分:1)

您不需要使用循环,您只需分钱,然后使用余数运算符从总金额中减去它。

可编辑的例子:

func interpretAsString(possibleMsg: Int32) -> String {
    var result = String()
    result.append(Character(UnicodeScalar(UInt32(possibleMsg>>24))!))
    result.append(Character(UnicodeScalar(UInt32((possibleMsg>>16) & UInt32(0xFF)))!))
    result.append(Character(UnicodeScalar(UInt32((possibleMsg>>8) & UInt32(0xFF)))!))
    result.append(Character(UnicodeScalar(UInt32((possibleMsg) & UInt32(0xFF)))!))
    return result
}

对于$ 255.50的输入,此代码打印此结果:

总变化金额:2 $ 100,

1 $ 50,

0 $ 20,

0 $ 10,

5 $ 1,

1 $ 0.50,

0 $ 0.20,

0 $ 0.10,

0 $ 0.05,

0 $ 0.02,

0 $ 0.01

编辑:显然这段代码可以进行很多改进,它可以作为如何进行计算的一个例子!

答案 1 :(得分:0)

假设你有这样的枚举:

enum CashType { c1, c5, c10, c25, c50, d1, d2, d5, d10, d20, d50, d100 }

你可以这样做:

var denominationsToCentValue = new Dictionary<CashType, int>()
{
    { CashType.d100, 10000 },
    { CashType.d50, 5000 },
    { CashType.d20, 2000 },
    { CashType.d10, 1000 },
    { CashType.d5, 500 },
    { CashType.d2, 200 },
    { CashType.d1, 100 },
    { CashType.c50, 50 },
    { CashType.c25, 25 },
    { CashType.c10, 10 },
    { CashType.c5, 5 },
    { CashType.c1, 1 }
};


var sortedCash = new Dictionary<CashType, int>();
var cashInRegister = 342.11M;
int cashInRegisterInCents = (int)(100 * cashInRegister);

foreach (var denom in denominationsToCentValue)
{
    int count = cashInRegisterInCents / denom.Value;
    cashInRegisterInCents -= count * denom.Value;

    sortedCash.Add(denom.Key, count);
}
相关问题