Question about math.floor


#1

How does this code work?

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

First we use Math.random() to create a random number from 0 up to 1. For example, 0.5
Then we multiply by 5 to make the random number from 0 up to 5. For example, 0.5 * 5 = 2.5
Next we use Math.floor() to round down to a whole number. For example, Math.floor( 2.5 ) = 2
Finally we add 1 to change the range from between 0 and 4 to between 1 and 5 (up to and including 5)

This doesn't work with 1, if the computer chooses the random number 1, then that's multiple by 5 which is 5 which doesn't need to be rounded and if you add 1 it's 6, so out of range

Where's my mistake?


#2

Math.random returns a random number between 0 (inclusive) and 1 (exclusive)


#3

Oh i understand, thank you


#4

you are welcome....... :slight_smile:


#5

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