4. I have to scan it more than once. Output gives correct total but I get an OOPS!


#1


I get the error message "It doesn't seem like your 'quantity' actually works!"
but the console logs "Your bill is 30.6" which seems like the correct output. What did I goof on?


var cashRegister = {
    total:0,
    add: function(itemCost){
        this.total += (itemCost);
    },
    scan: function(item, quantity){
        for ( i = 0; i < quantity; i++){
        switch (item) {
        case "eggs": this.add(0.98); break;
        case "milk": this.add(1.23); break;
        case "magazine": this.add(4.99); break;
        case "chocolate": this.add(0.45); break;
        };
        };
    }
};

// scan each item 4 times
cashRegister.scan("eggs", 4);
cashRegister.scan("milk", 4);
cashRegister.scan("magazine", 4);
cashRegister.scan("chocolate", 4);


//Show the total bill
console.log('Your bill is '+cashRegister.total);


#2

You didn't goof.

It tests this:

var oldTotal = cashRegister.total;
cashRegister.total = 0;
cashRegister.scan("eggs", 1);
cashRegister.scan("milk", 2);
cashRegister.scan("magazine", 3);
cashRegister.scan("chocolate", 4);
if(cashRegister.total !== 20.21) {
    return "It doesn't seem like your 'quantity' actually works!";
}

See what it does at the bottom?

Your actual result is 20.209999999999997

Floats cannot represent all numbers, testing if your result is exactly equal to something is incorrect behaviour because it's going to be an approximation.

I think you might pass if you use multiplication instead of repeatedly adding. You could also "cheat" (not really cheating, it's circumventing a broken test) by having your scan function set the total to 20.21 regardless of arguments, and setting cashRegister.total to 30.6 at the end of your code

Another alternative is to multiply amounts by 100 while doing operations so to only deal in integers, and then dividing by 100 again. That still doesn't make it exact but all the intermediary steps while the function is adding things up would be exact, the dividing by 100 afterwards still messes that up.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.