Why not Math.ceil(()?


#1

https://www.codecademy.com/courses/javascript-beginner-en-mrTNH-6VIZ9/0/1?curriculum_id=506324b3a7dffd00020bf661

Why would you use floor instead of ceiling here?
Basically, if you hit the dragon 4 or 5 damage, you kill it, but if less you keep playing until you kill it or it kills you (I think?). But why use floor +1 rather than ceil? I understand that ceil() would take 4.0 and turn it into 4, and floor +1 would take 4.0 and turn it into 5, but any hit more than 4 will kill the dragon, so why use floor rather than ceil? Is this common? Is this a standard usage?
(I realize that 3.0 will round up to a killing hit with floor()+1 and not with ceil(), but what are the chances that random() will return exactly 3.0? Literally, how many decimal places does random() return?)

Here is the code from the tutorial

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!");
    totalDamage += damageThisRound;
    
    if (totalDamage >= 4) {
      console.log("You did it! You slew the dragon!");
      slaying = false;
    } else {
      youHit = Math.floor(Math.random() * 2);
    }
  } else {
    console.log("The dragon burninates you! You're toast.");
    slaying = false;
  }
}

#2

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