Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Help ! I did the method, and ask a number between 4 and 6. And it gives me 4, or 6 inclusive.

var starting_input = prompt("Please, tell me a starting number");
var finish_input = prompt("Please, tell me a limit number");

var bottomNumber = parseInt(starting_input);
var topNumber = parseInt(finish_input);

var randomNumber = Math.floor(Math.random() * (topNumber - bottomNumber + 1)) + bottomNumber;
alert( randomNumber + " is a number between " + starting_input + " and " + finish_input);

Well, If I put 4 and 6 as my limits. I would like the answer to be 5 as an number between 4 and 6. But instead, the (Math.random() * (topNumber - bottomNumber + 1) gives a number between 0 and 2.99999. And with the math floor, gives an number between 0 a 2.

How can I make the range between 1 and 1.99999. So I can add the bottom number (4) and have the 5 as an answer ?

1 Answer

Steven Parker
Steven Parker
243,656 Points

You just need to implement a different formula.

This is the formula for inclusive random ranges:

(random * (topNumber - bottomNumber + 1)) + bottomNumber

And this is the formula for exclusive random ranges:

(random * (topNumber - bottomNumber - 1)) + bottomNumber + 1

Great!!! Thank you so much!