totalDamage += damageThisRound is equalling weird numbers


#1

If I get 1 damage the first round and 1 damage the second round, second round total damage will show '11' and not '2'

This seems weird. Anyone else experience this / know what i'm doing wrong?


#2

Let's see your code pls


#3

Not sure if there's an accepted way to post code (first time in the forums) but here you go:

var slaying = true
var youHit = Math.floor(Math.random() * 2)
var damageThisRound = Math.floor(Math.random() * 5+1)
var totalDamage = 0

while(slaying){
    if(youHit){
        console.log("You hit the dragon and did" + " " + damageThisRound + " " + "damage!");
        console.log("Total damage:" + " " + totalDamage + damageThisRound);
        totalDamage+=damageThisRound;
        if(totalDamage >= 4){
            console.log("You Win!");
        slaying = false;
    }
    else{
        youHit = Math.floor(Math.random() * 2);
    }
    }
    else{
        console.log("The dragon burninated you!");
        slaying = false;
    }
};

Thank you!!


#4

Have a look at how it is done here :slightly_smiling:

From what I can see I'd guess that it is working and just the error message is false. The problem is that + means both + in the mathematical meaning and string concatenation. So if one part of the equation is a string it means string concatenation. Now have a look at your output message:

"Total damage:" + " " + totalDamage + damageThisRound

And go through it from left to right, then you see that it is always string concatenation. So what you can do is increase the priority by adding () around your calculation:

console.log("Total damage:" + " " + (totalDamage + damageThisRound) );

now it is still string concatenation, but this time (totalDamage + damageThisRound) is a block that gets evaluated before being appended to the string.


#5

ahhh got it. Thanks! :slightly_smiling: