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 JavaScript Basics (Retired) Working With Numbers The Random Challenge

Reza Zandi
seal-mask
.a{fill-rule:evenodd;}techdegree
Reza Zandi
Full Stack JavaScript Techdegree Student 1,599 Points

Just 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
Steven Parker
229,670 Points

FYI: 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
seal-mask
.a{fill-rule:evenodd;}techdegree
Reza Zandi
Full Stack JavaScript Techdegree Student 1,599 Points

Ah, 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
Steven Parker
229,670 Points

Both formulas include the min.

Steven Parker
Steven Parker
229,670 Points

The +1 is what includes the max. The "floor" function (essentially "round down") is what gives you only integers.