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 JavaScript Basics (Retired) Working With Numbers The Random Challenge

Miguel Fernando
Miguel Fernando
12,850 Points

Simple solution?

Just posting my simplest solution for the challenge.

var lowerLimit = parseInt(prompt("Enter an integer as a lower limit")); var upperLimit = parseInt(prompt("Enter an integer as an upper limit")); var randomNumber = Math.floor(Math.random() * (upperLimit - lowerLimit)) + lowerLimit; document.write(randomNumber);

1 Answer

Hey Miguel Fernando,

You are very close with your answer to this challenge! The problem is that with the code you have there, the random number can never be the maximum value possible in the range of random numbers to generate. The reason being that the highest value that the Math.random() function can return is 0.9999.... So, let's say we want a number in between 50 and 100, inclusive. Let's say we roll Math.random() to be 0.99999.... and do the math here.

Math.floor(0.9999... * (100-50)) + 50 which turns into Math.floor(49.9995) + 50. That then evaluates to "49 + 50" which is 99.

In order to get to that last possible upperLimit, all you have to do is add 1 to your (upperLimit - lowerLimit) statement like so:

var lowerLimit = parseInt(prompt("Enter an integer as a lower limit")); 
var upperLimit = parseInt(prompt("Enter an integer as an upper limit")); 
var randomNumber = Math.floor(Math.random() * (upperLimit - lowerLimit + 1)) + lowerLimit; 
document.write(randomNumber);

This will allow 49 to become 50 for the maximum possible roll and thus allow 100 into the accepted possible outcomes. I hope that makes sense! :)

Miguel Fernando
Miguel Fernando
12,850 Points

That's great, thanks! I got some clarification when watching the solution video too after posting.

Excellent! Well, then I wish you happy coding! :)