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 trialLucas Huerta-Murillo Grau
Courses Plus Student 1,365 PointsWhy can't you change the +1 to the minimum instead?
My code:
var ceilLimit = prompt("Choose a maximum number");
var floorLimit = prompt("Choose a minimum number");
var maxNum = parseInt(ceilLimit);
var minNum = parseInt(floorLimit);
var randomNum =
Math.floor( Math.random() * maxNum) + minNum;
document.write("Your random number is " + randomNum);
2 Answers
Steven Parker
231,275 PointsIf you add 1 to the minimum, you would get the wrong range.
You want the formula to pick a number that is at least the minimum, but no greater than the maximum. If you add one to the minimum, the formula would never be able to pick it.
On the other hand, you must add one to the range for the range to include both ends. Your formula is still missing a correct range calculation, but here's one that would do the job:
var randomNum = Math.floor( Math.random() * (maxNum - minNum + 1) ) + minNum;
Devjyoti Ghosh
2,422 PointsIf you add minimumNumber instead of +1 what happens is Math.floor will return a value from 0 to maximumNumber. When you add minimumNumber to this your range changes to minimunNumber to (maximumNumber+minimumNumber).
for eg for a range between 10 to 30
your code will give a range from 10 to 40.
edit: it should be 10-39 as Math.random gives you random number between 0-1 but not 1 itself so Math.floor will reduce the range down to maximumNumber -1.
Steven Parker
231,275 PointsActually, the code originally shown would give a number within 10 to 39.
Devjyoti Ghosh
2,422 PointsYou are right Steven I forgot Math.random doesn't output the value 1.