简体   繁体   English

确切的变化-FreeCodeCamp挑战

[英]Exact change - freecodecamp challenge

I'm trying to solve Freecodecamp challenge: 我正在尝试解决Freecodecamp的挑战:

Design a cash register drawer function checkCashRegister() that accepts purchase price as the first argument (price), payment as the second argument (cash), and cash-in-drawer (cid) as the third argument. 设计一个收银机抽屉函数checkCashRegister(),该函数将购买价格作为第一个参数(价格),将付款作为第二个参数(现金),并将现金入库(cid)作为第三个参数。

I've almost solved it, problem is that it doesn't substract, for example "Twenty" as many times as it should. 我几乎解决了这个问题,问题在于它并没有减去它,例如“二十”应有的次数。

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]]) should return [["TWENTY", 60.00], ["TEN", 20.00], ["FIVE", 15.00], ["ONE", 1.00], ["QUARTER", 0.50], ["DIME", 0.20], ["PENNY", 0.04]].

It should substract 20$ three times or 60$ , it substracts just once. 它应该减去20美元的三倍或60美元,它只减去一次。

It returns: 它返回:

   [["TWENTY", 20.00], ["TEN", 10.00], ["FIVE", 5.00], ["ONE", 61.00], ["QUARTER", 0.50], ["DIME", 0.20], ["PENNY", 0.04]]

60$ is added to "ONE" .. 60美元添加到“一个” ..

 function checkCashRegister(price, cash, cid) { var change = cash - price; var changeArray = []; var val = 0; var n = [ {name:"PENNY",value:0.01}, {name:"NICKEL",value:0.05}, {name:"DIME",value:0.10}, {name:"QUARTER",value:0.25}, {name:"ONE",value:1.00}, {name:"FIVE",value:5.00}, {name:"TEN",value:10.00}, {name:"TWENTY",value:20.00}, {name:"ONE HUNDRED",value:100.00} ]; var den = n.reverse(); var register = cid.reduce(function(accumulator, next) { return accumulator+next[1]; }, 0); if(register === change) { return "Closed"; }else if(register < change) { return "Insufficient Funds"; } else { } for(var i=0;i<cid.length;i++) { val=0; while(cid[i][1] >= 0 && change >= den[i].value) { change -= den[i].value; change = Math.round(change * 100) / 100; cid[i][1] -= den[i].value; val += den[i].value; } if(val !== 0) { changeArray.push([den[i].name, Number(val.toFixed(2))]); } } if(changeArray.length < 1 || change > 0) { return "Insufficient Funds"; } return changeArray; } 

while(cid[i][1] >= 0 && change >= den[i].value)

Maybe I missed something in your code, but aren't cid[i][1] and den[i].value ordered oppositely? 也许我错过了您的代码中的某些内容,但是cid[i][1]den[i].value顺序不是相反吗? Also, wouldn't cid[i][1] have to be at least as much or more than den[i].value ? 另外, cid[i][1]是否必须至少等于或大于den[i].value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM