我需要一些帮助。我正在freecodecamp“收银机”上做篝火晚会。我的代码应该工作,因为它返回的是freecodecamp的要求,但是由于某些原因,即使两个答案相同,它也表示我的代码是错误的。有人可以看一下我的代码,让我知道哪里出了问题吗?
let cashValue = [
{name:"ONE HUNDRED", value:100},
{name:"TWENTY", value:20},
{name:"TEN", value:10},
{name:"FIVE", value:5},
{name:"DOLLAR", value:1},
{name:"QUARTER", value:0.25},
{name:"DIME", value:0.1},
{name:"NICKEL", value:0.05},
{name:"PENNY", value:0.01}
]
function checkCashRegister(price, cash, cid) {
var change = cash -price;
console.log(change);
let total = parseFloat(cid.reduce((acc,next)=>{return acc +
next[1]},0.0)).toFixed(2);
let changeStatus = {status:"", change:[],};
if(total<change){
return {status: "INSUFFICIENT_FUNDS", change: []};
} else if(total == change){
return {status: "CLOSED", change: cid};
} else {
cid = cid.reverse();
cashValue.forEach((next,index)=>{
if(change >= next.value){
let currentValue = 0.0;
while(change>=next.value && cid[index][1]>=next.value){
currentValue += next.value;
change -= next.value;
change = Math.round(change * 100)/100;
cid[index][1] -=next.value;
}
changeStatus.status = "OPEN";
changeStatus.change.push([next.name,currentValue]);
}
});
} //console.log(change);
if(change !== 0){
changeStatus.status = "INSUFFICIENT_FUNDS";
changeStatus.change = [];
}
return changeStatus;
}
checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05],
["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55],
["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);
// Should return {status: "OPEN", change: [["TWENTY", 60], ["TEN",
20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}
答案 0 :(得分:0)
是的,您的代码很好。在这里,我从控制台日志中复制了它。
change 96.74
0: (2) ["TWENTY", 60]
1: (2) ["TEN", 20]
2: (2) ["FIVE", 15]
3: (2) ["DOLLAR", 1]
4: (2) ["QUARTER", 0.5]
5: (2) ["DIME", 0.2]
6: (2) ["PENNY", 0.04]
尝试将单打的变量名从DOLLAR更改为ONE,就像Johnny所说的那样,您应该通过...