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 trialJay Valentine
Courses Plus Student 4,389 PointsReally struggling with this :/
Here is my code
alert("This is the Random Number Generator... All you have to do is pick 2 numbers, and my automated script, will randomly select a number inbetween your chosen numbers!");
var numberOne = prompt('Please type your first whole number');
var bottomNumber = parseInt(numberOne);
var numberTwo = prompt('Please enter your second whole number(Must be a bigger number than the first)');
var topNumber = parseInt(numberTwo);
var diceRoll = Math.floor(Math.random() * (topNumber - bottomNumber + 1)) + bottomNumber;
var message = "" + diceRoll + " is a number between " + bottomNumber + " and " + topNumber + ".";
document.write(message);
i just cant seem to wrap my head around it, i dont really understand this bit below!, which is the main bit haha! can someone explain please in laymens terms
var diceRoll = Math.floor(Math.random() * (topNumber - bottomNumber + 1)) + bottomNumber;
var message = "" + diceRoll + " is a number between " + bottomNumber + " and " + topNumber + "."
1 Answer
Joshua Woehlke
8,260 PointsThese random number lines can get confusing, so let's break it down first by that inner part. Say we wanted a number between 10 and 20:
Math.random() * (20 - 10 + 1)
This gives you Math.random() * 11
, which means you'll have a random number 0-1 (really 0 - 0.9999....) multiplied by 11.
You may end up with 0.1232, or 10.2312; all of these values will fall within the above range.
Next, you wrap Math.floor()
around that expression so that whatever number you receive, its decimal places are removed. This means those numbers we saw above will come out as 0 and 10.
Lastly, you're adding your bottom range to whatever was in the Math.floor()
, so in this example, 10 + a random number 0-10, which satisfies our requirements.
This will become second nature after a while, but just remember that if you want a random number 0-10, you'd actually want to multiply Math.random()
by 11 and then floor it (that way your Math.random()
can hit numbers higher than 10, like 10.5323), whereas if you wanted a random number 1-10, you'd multiply Math.random()
by 10, add 1 to the result, and then floor it.
geoffrey
28,736 Pointsgeoffrey
28,736 PointsWell explained +1 !