Help me understand Generate Random Whole Numbers within a Range Challenge

HI I am stuck understanding this challenge because it is complicated a little bit when it comes to understanding this line

return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;

I need help to understand this line and how it works exactly

Hi Hamza-Noah,

  • Math.floor rounds numbers down. For example Math.floor(2.5) = 2
  • Math.random returns a “random” number between 0 and 1. For example, it could return 0.1.

Let’s use an example to understand the formula that you have here.

randomRange(3, 5)           with Math.random() = 0.2
Math.floor(0.2 * (5 - 3 + 1)) + 3
Math.floor(0.2 * (3)) + 3
Math.floor(0.6) + 3
0 + 3
3

best,
Dennis

1 Like

Hi @Hamza-Noah !

I edited your post to include the challenge link.
I also edited the title of your post to remove the link.
Please avoid placing links in the title since we cannot click on them.


I also found a helpful article on how Math.random works in the context of a game like the dice game.
I think when you see it working in the context of an actual project then it will start to make more sense.

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