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

hi! Solution of challenge with random number between two user's numbers. Is it correct?

var topNumber = prompt("INSERT TOP NUMBER");
topNumber = parseInt(topNumber);
var bottomNumber = prompt("INSERT BOTTOM NUMBER");
bottomNumber = parseInt(bottomNumber);

var randomNumber = Math.random();
var betweenNumber = Math.floor(randomNumber * topNumber + bottomNumber - randomNumber);
document.write("<h1 style='color:red;'>" + betweenNumber + " — number between " + bottomNumber + " and " + topNumber + "</h1>");

4 Answers

From the documentation on Math.random()...example for number between 1 and 100... Math.floor((Math.random() * 100) + 1);

I'm not sure about the last bit you have ... " + bottomNumber - randomNumber" in the Math.floor line. I think you just want to add the bottom number and not subtract your random number.

Steven Parker
Steven Parker
243,318 Points

You're close, but not quite right.

The way to convert a random number between 0 and 1 (exclusive) to an arbitrary range is like this:
random * range + minimum,   where range is:   maximum - minimum + 1.

:point_right: So for your code, replace line 7 with this:

var betweenNumber = Math.floor(randomNumber * (topNumber - bottomNumber + 1) + bottomNumber);

Thx for the attention Steven, Karen. But it is not so clear for beginner (very hard to understand without math explanation of the MAGIC: " range is: maximum - minimum + 1"). It looks like theorem not axiom. Spent hour trying to understand why is that so.

And also challenging to prove that there is no other solution but you came up with:

var betweenNumber = Math.floor(randomNumber * (topNumber - bottomNumber + 1) + bottomNumber);

Many times there are more than one solution that works! Looks like you found a good one there, did it give you the results you expected?

it works fine for me, Karen but still I wanna be SURE it IS CORRECT solution Than's why I am here) You gave me some confidence here with «there are more than one solution that works!» 10x http://port-80-lpl61f2f4x.treehouse-app.com