Cash Register challenge: Almost works, don´t have idea why doesn´t work 100%

To not bother you with all the code, here´s an extract code which It is supposed to fill the variable “MoneyReceiver” with 97.74

var MoneytoSend = 97.74
  var MoneyReceiver = 0 
  var TypeofCurrency = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100]
  var MoneyinCurrency= [101, 41, 31, 17, 90, 11, 2, 3, 1]
  
  function SendMoney(){
     for (var i = 7; i > -1; i--){
         let counter = MoneyinCurrency[i]
         for (var j=0; j<counter;j++){
            if (MoneyReceiver > MoneytoSend ){
             MoneyReceiver -= TypeofCurrency[i]
              return MoneyReceiver}
            else {
            MoneyReceiver += TypeofCurrency[i]
            }
           }
  }
  }

SendMoney()

MoneyReceiver // returns 95

// MoneyReceiver returns just 95. (it should return 97.74)

It works nice going from 20, to 10, to 5, but then it just stops there. Why it doesn´t take also 1 dollar and keeps adding?

hello @Onpointiscake,

I recently completed this challenge over the weekend. Could you include more of your code?

The problem here is with your second ‘for’ loop. You are returning a value as soon as MoneyReceiver is greater than MoneytoSend (remember to use camelCase on variables). You don’t want to RETURN a value, you simply want to exit the ‘for’ loop. Therefore, a while loop might be more appropriate. Your second loop could be a while loop to test for the condition in which typeOfCurrency[i] + moneyReceiver < moneyToSend while true, add typeOfCurrency[i]. If false, the while loop will automatically be ignored and move to a smaller currency on the outer loop. You could also keep the ‘for’ loop and use a break statement to jump out of the loop. Currently your code is adding 20 + 20 + 20 + 10 + 10 + 5 + 5 + 5 + 5, which is going to 100, then testing true and RETURNING 100 - 5 and therefore ending the function altogether.

Also, remember you need to track the number of bills/coins returned for each currency and store them in an object.

Lastly, you’ll likely encounter a problem with rounding when you get to dimes or pennies. This is because it is impossible to represent 0.1 in binary. You’ll need to convert dollars to cents so you are only working with integers.

I also recommend adding some console.log statements throughout your code so you can visualize the loops. Something like console.log('outer loop: ' + typeOfCurrency[i]) and console.log(moneyReceiver) in the inner loop.

Hopefully this is helpful. Happy coding :slight_smile:

what the hell dude, I JUST have to remove the line “return MoneyReceiver” inside the second for loop as you said, and it worked perfectly! lol

You gotta love this sh** :grimacing::joy:

1 Like