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 trialReza Zandi
Full Stack JavaScript Techdegree Student 1,599 PointsJust posting my answer
So, the first part was easy, but then it got tricky when I needed to figure out how to take the input for the minimum value of the range as well. I'm used to python, and it would of been easy to do but since js is a different language, I had to look up MDN.
function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min;
so, I simply made another user prompt for min. Half the time I was simply debugging simple errors rather than figuring out the logic.
Here's my actual code
var userMaxInput = parseInt(prompt("input a number to use for the Max number for the desired range of the random number generator"))
var userMinInput = parseInt(prompt("input a number to use for the Min number for the desired range of the random number generator"))
var randomNumber = Math.random() * (userMaxInput-userMinInput) + userMinInput;
document.write(randomNumber)
3 Answers
Steven Parker
231,271 PointsFYI: this formula from MDN returns a floating-point number that "is less than (and not equal) max
". But a perhaps more common implementation (and what is shown in the video) chooses only an integer number, and it can include the max
value:
function getRandomIntegerInRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Reza Zandi
Full Stack JavaScript Techdegree Student 1,599 PointsAh, ok, I see, because we want to include the max. Can it also include the min? Or is it everything above the min and including the max?
Steven Parker
231,271 PointsBoth formulas include the min.
Reza Zandi
Full Stack JavaScript Techdegree Student 1,599 PointsAnd I understand what I did, I wasn't rounding to an integer. Which is why you need that +1
Steven Parker
231,271 PointsThe +1 is what includes the max. The "floor" function (essentially "round down") is what gives you only integers.