Why Math.random() *2?


#1

Hi, could someone explain my why we are multiplying Math.random() by 2? and then by 5? why we have to multiply?


#2

Also said in the instructions, there is

Math.random()*2

so JavaScript can look at the random number that the computer made. Doing Math.random()*2, you can get a random number of 0 or 1, which JavaScript reads as false (0) and true (1).

This:

Math.floor(Math.random() * 5 + 1)

is used so it sets a variable (in this case, damageThisRound) to set a random number between 1 and 5.

This is said when you click the "Hint" button:

How does this code work?

Math.floor(Math.random() * 5 + 1);

1.First we use Math.random() to create a random number from 0 up to 1. For example, 0.5

2.Then we multiply by 5 to make the random number from 0 up to 5. For example, 0.5 * 5 = 2.5

3.Next we use Math.floor() to round down to a whole number. For example, Math.floor( 2.5 ) = 2

4.Finally we add 1 to change the range from between 0 and 4 to between 1 and 5 (up to and including 5)

Hope it helped!:smiley: