function checkCashRegister(price, cash, cid) {
var change = cash - price; //该找补的钱
var changeLeft = change; //每轮找补之后还该找补的钱
var subCid = 0; //收银机里所有零钱的和
var obj = { //面值单位
"PENNY": 0.01,
"NICKEL": 0.05,
"DIME": 0.1,
"QUARTER": 0.25,
"ONE": 1,
"FIVE": 5,
"TEN": 10,
"TWENTY": 20,
"ONE HUNDRED": 100
};
var result = []; //最后返回的结果
function sum(cid){ // 求和函数
var total = 0;
for(var i = 0;i<cid.length;i++){
total += cid[i][1];
}
return total.toFixed(2);
}
subCid = sum(cid);
if(subCid < change){
return "Insufficient Funds";
}else if(change - subCid ===0){
return "Closed";
}
for(var j=cid.length-1;j>=0;j--){
var coinName = cid[j][0]; //零钱面额名称
var coinTotal = cid[j][1]; //该面额零钱之和
var coinValue = obj[coinName]; //零钱面额单位
var coinAmount = coinTotal/coinValue; //该面额零钱张数
var toReturn = 0; //找回零钱张数
while(changeLeft>=coinValue && coinAmount>0){
changeLeft-=coinValue;
changeLeft = changeLeft.toFixed(2); // 处理小数相减出现一长串的小数位数
coinAmount --;
toReturn ++;
}
if(toReturn > 0){
result.push([coinName,toReturn*coinValue]);
}
}
if(changeLeft!=0){
return "Insufficient Funds";
}
return result;
}
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3, 4.25],
// ["ONE", 90.00],.10],
// ["QUARTER"
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]
checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);