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 trialEric Jusic
4,350 PointsAnother solution with 2 inputs, what do you say?
Here is my code for randomizing between 2 inputs, which seems to work:
var lowestNumber = parseInt(prompt("Pick lowest number.")); var userInput = parseInt(prompt("Insert number you want to randomize.")); var rollNumber = Math.floor( Math.random() * (userInput - lowestNumber) ) + lowestNumber; var result = "The random number you got is " + rollNumber; alert(result);
If you have any better solution please suggest.
Thank you :)
3 Answers
Steven Parker
231,275 PointsTwo suggestions:
Add 1 to the range to make it inclusive:
"Math.floor(Math.random() * (userInput - lowestNumber
+ 1
) ) + lowestNumber"
For clarity, you might want to ask for "highest number" instead of "number you want to randomize."
Eric Jusic
4,350 PointsThanks Steven for answering.
Can you clarify why this +1 is there? Is this because of Math.random() can give 0 potentially? Even if it gives 0 + lowestNumber will be the lowestNumber? Or I am missing something?
I agree on the second suggestion, I just named it that way in the workspace.
Steven Parker
231,275 PointsRemember that Math.random generates values approaching but never equal to 1. So when you multiply it by another value, the product will approach but never equal that number. By adding 1, that allows the range to include the high number in the possible values instead of just generating numbers up to but not including that number.
Eric Jusic
4,350 PointsGot it now, I forgot on the highest one.
Thank you, Steven, for helping me out again :)