Concept of Math.floor(Math.random() * 5 + 1), what is the true range and why?

后端 未结 4 692
南方客
南方客 2021-01-05 15:39

By multiplying the random number (which is between 0 and 1) by 5, we make it a random number between 0 and 5 (for example, 3.1841). Math.floor() rounds this number down to a

4条回答
  •  心在旅途
    2021-01-05 16:12

    Math.Random() returns a number between 0 and 1, excluding 1.

    So when you multiply it with 5, you get a number between 0 and 5 but not 5.

    Math.floor() on this number rounds down to a whole number.

    So numbers you will get are either 0, 1, 2, 3 or 4.

    Adding 1 to this range gives you a number in [1, 2, 3, 4, 5].

提交回复
热议问题