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 Solution

Chougui Younes
Chougui Younes
2,028 Points

Why Mr. Dave Add bottomnumber

i want to know why Mr's Dave Add bottom Number In Line 5 plz

var input1 = prompt("please type a starting number");
var bottomNumber = parseInt(input1);
var input = prompt('Put A Number Please');
var topNumber = parseInt(input);
var randomNumber = Math.floor(Math.random() * (topNumber-bottomNumber + 1)) + bottomNumber ;
var message = "<h1>" + randomNumber + "is a number between " + bottomNumber + "and" + topNumber + ".</h1>";

2 Answers

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,252 Points

Hi there,

what the program is doing is outputting a random number, between the 2 numbers the user types. so it could be a number between 7 and 4, one number being higher than the other.

Hope this helps,

By the way I edited your post to display the code clearly using Markdown. Checkout the link that says Markdown Cheatsheet for all the info you need on how to use it yourself. Good luc . :)

Stan Ponkin
Stan Ponkin
1,764 Points

Let's assume that the user types in 4 (for bottomNumber) and 7 (for topNumber).

If we multiple Math.random() by 7 + 1, we will get anything between 1 and 7, which is incorrect. We need random number that falls between 4 and 7.

To do that, first we need to subtract 4 (bottomNumber) from 7 (topNumber), which equals to the RANGE between 7 and 4 (=3). Then we need to multiply 3 by Math.random(), for simplicity, let's say random number equals 0.5000 Finally, we add 4 (bottomNumber) to the result. This way we will never fall below 4.

(7-4) = 3 3 * .5 = 1.5 (1.5 + 4) = 5.5

I think it's easier to run a few examples to understand the math.

Thank you,