一、问题还原
商场买东西的时候,营业员需要找零。现在有面额为100元、50元、20元、10元、5元、2元、1元、5角、2角、1角,5分,2分和1分的人民币若干,问,如何找零才能使现金最优发放(也就是说同一找零金额下,找零发放的人民币数量最少)。
二、经典解法
实现如下:
代码
class Program
{
//人民币面额
private static decimal[] moneyArr = new decimal[] { 100M, 50M, 20M, 10M, 5M, 2M, 1M, 0.5M, 0.2M, 0.1M, 0.05M, 0.02M, 0.01M };
//存各种面额的人民币发放份数
private static int[] moneyCountList = null;
static void Main(string[] args)
{
decimal currentMoney = 188.88M;
int[] moneyCount = Calculate(currentMoney);
Console.WriteLine("当前需找零金额:{0}¥", currentMoney);
for (int i = 0; i < moneyCount.Length; i++)
Console.WriteLine("面额{0}¥ 共 {1} 张", moneyArr[i], moneyCount[i]);
Console.ReadLine();
}
/// <summary>
/// 计算发放金额数
/// </summary>
/// <param name="money"></param>
/// <returns></returns>
static int[] Calculate(decimal money)
{
moneyCountList = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int tmpMoney = NumHelper(money);
while (tmpMoney > 0)
{
for (int i = 0; i < moneyArr.Length; i++)
{
if (tmpMoney >= NumHelper(moneyArr[i]))
{
tmpMoney -= NumHelper(moneyArr[i]); //减去一份发放的面额
moneyCountList[i] += 1;//对应的发送份数+1
break;
}
}
}
return moneyCountList;
}
/// <summary>
/// 将金钱转换成整数处理
/// </summary>
/// <param name="money"></param>
/// <returns></returns>
static int NumHelper(decimal money)
{
return Convert.ToInt32(money * 100);
}
}
留言区(共0条)