设计一个收银程序 checkCashRegister()
,其把购买价格(price
)做为第一个参数 , 付款金额 (cash
)做为第二个参数, 和收银机中零钱 (cid
) 做为第三个参数.javascript
cid
是一个二维数组,存着当前可用的找零.java
当收银机中的钱不够找零时返回字符串 "Insufficient Funds"
. 若是正好则返回字符串 "Closed"
.git
不然, 返回应找回的零钱列表,且由大到小存在二维数组中.github
思路:数组
1.remainder表示剩余要找的钱,arr里放须要的零钱数组,value表示总共要找的钱的总值。这里要分清value总值和total总值。app
2.用循环计算出数组里的钱,用total来表示零钱总值,要明白cid[i][1]存放的是该零钱的价值,就很好理解了,第一层循环条件同时保证该零钱有值,且找到知足要找钱的最大数组的值。优化
3.在循环中由于从大到小,就只要考虑,c表示能够找的最大零钱的个数,若是要找的钱大于了当前已有最大数组的值,则相减后,把当前数组放入arr[j]并让j自加,若是小于,就减掉当前数组最多能减掉的值并把将当前零钱的价值写给数组,最后把它赋给arr[j]。由于减法运算可能会形成浮点不许确,因此要每次循环都添加toFixed保留两位小数。设计
4.最后把判断return的语句添上,要注意第二个判断必须是!=,不能用!==,有可能remainder为0.00的状况,而这种状况也不能用parseInt去取正。code
let checkCashRegister = (price, cash, cid) => { let remainder = cash - price,arr = [],j = 0,total = 0 ,value = remainder; const array = [0.01,0.05,0.1,0.25,1,5,10,20,100]; for(let i = cid.length - 1;i >= 0;i--){ total += cid[i][1]; if(remainder > array[i] && cid[i][1] > 0){ let c = parseInt(remainder / array[i]); if(remainder > cid[i][1]){ remainder -= cid[i][1]; }else{ remainder -= c * array[i]; cid[i][1] = c * array[i]; } remainder = remainder.toFixed(2); arr[j++] = cid[i]; } } if(total === value){ return "Closed"; }else if(total < value || remainder != 0){ return "Insufficient Funds"; } return arr; }; console.log(checkCashRegister(19.50, 20.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]])); //[["QUARTER", 0.5]]
若是有不明白的地方请留言,若是有更好更简便更优化的方法请留言,谢谢。blog
更多内容请访问个人我的博客: Bblog