Tell us what’s happening:
Hi There! I am getting a very strange behaviour from this piece of code. I don’t really need help solving the problem, i’ll figure that out in a different way. It’s just that when I run this code, there seems to be an error when substracting somewhere in the while loop. And I don’t get it.
Maybe someone here is willing to try and figure out what happens. I’m just really curious where it goes wrong.
Below is my code and below that is part of the console log.
Thanks in advance for any help!
Your code so far
function checkCashRegister(price, cash, cid) {
console.log("start");
var cidTotal = 0;
var changeTotal = cash - price;
var change = 0;
var length = cid.length;
var nMoney = length-1;
cid.forEach(function(value){
switch(value[0]){
case "PENNY":
value[0] = 0.01;
break;
case "NICKEL":
value[0] = 0.05;
break;
case "DIME":
value[0] = 0.1;
break;
case "QUARTER":
value[0] = 0.25;
break;
case "ONE":
value[0] = 1;
break;
case "FIVE":
value[0] = 5;
break;
case "TEN":
value[0] = 10;
break;
case "TWENTY":
value[0] = 20;
break;
case "ONE HUNDRED":
value[0] = 100;
break;
}
});
console.log(cid[0]);
console.log(cidTotal);
while(changeTotal > 0 && nMoney > -1){
console.log(cid[nMoney][1]);
if((cid[nMoney][1]) > 0){
console.log("changeTotal: " + changeTotal);
console.log("cid[nMoney][0]: " + cid[nMoney][0]);
console.log("cid[nMoney][1]: " + cid[nMoney][1]);
changeTotal -= cid[nMoney][0];
cid[nMoney][1] -= cid[nMoney][0];
} else {
nMoney--;
}
}
return cid;
}
checkCashRegister(19.50, 20.00, [["PENNY", 0.50], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]);
20:25:41.796 VM460:47 0.5
20:25:41.796 VM460:49 changeTotal: 0.5
20:25:41.796 VM460:50 cid[nMoney][0]: 0.01
20:25:41.797 VM460:51 cid[nMoney][1]: 0.5
20:25:41.797 VM460:47 0.49
20:25:41.797 VM460:49 changeTotal: 0.49
20:25:41.797 VM460:50 cid[nMoney][0]: 0.01
20:25:41.797 VM460:51 cid[nMoney][1]: 0.49
20:25:41.797 VM460:47 0.48
20:25:41.797 VM460:49 changeTotal: 0.48
20:25:41.797 VM460:50 cid[nMoney][0]: 0.01
20:25:41.797 VM460:51 cid[nMoney][1]: 0.48
20:25:41.798 VM460:47 0.47
20:25:41.798 VM460:49 changeTotal: 0.47
20:25:41.798 VM460:50 cid[nMoney][0]: 0.01
20:25:41.798 VM460:51 cid[nMoney][1]: 0.47
20:25:41.798 VM460:47 0.45999999999999996
20:25:41.798 VM460:49 changeTotal: 0.45999999999999996
20:25:41.798 VM460:50 cid[nMoney][0]: 0.01
20:25:41.798 VM460:51 cid[nMoney][1]: 0.45999999999999996
20:25:41.798 VM460:47 0.44999999999999996
20:25:41.798 VM460:49 changeTotal: 0.44999999999999996
20:25:41.799 VM460:50 cid[nMoney][0]: 0.01
20:25:41.799 VM460:51 cid[nMoney][1]: 0.44999999999999996
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
.
Link to the challenge:
https://www.freecodecamp.org/challenges/exact-change