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
Bob Allan
10,900 PointsStrange random results ... what am I missing?
I'm stumped! What am I doing wrong? The results a strange numbers above the upper input number. Thanks in advance for your help.
function randomBetweenNumbers( upper, lower ) { return Math.floor(Math.random() * (upper - lower +1)) + lower; }
var foo = prompt("What is the upper number?"); var bar = prompt("What is the lower number?"); document.write( randomBetweenNumbers( foo , bar ) );
2 Answers
tobiastrinkler
Full Stack JavaScript Techdegree Student 16,538 PointsHi Bob,
You are almost there you just have to use the parseInt() method to convert the string to a number.
function randomBetweenNumbers( lower, upper ) {
return Math.floor(Math.random() * (upper - lower +1)) + lower; }
var foo = parseInt(prompt("What is the upper number?"));
var bar = parseInt(prompt("What is the lower number?"));
document.write( randomBetweenNumbers(foo,bar) );
Shay Paustovsky
969 PointsHi there,
It generates above the input number because the 'lower' paramater is outside the statement that generates the random number.
It should look like this:
function getRandomNum(upper, lower) {
return Math.floor(Math.random() * (upper - lower) + lower)
}
Let me explain : So first the statement generates a random number with the given difference from the function's arguments, then it adds the 'lower' paramater argument ( think of it like the 1), and then rounds up the difference because Math.random() returns a floating-point/decimal random number value.
Hopefully I've helped
Shay
Bob Allan
10,900 PointsIn my frustration I forgot to explain exactly what I wanted the code to accomplish (looking for a random number between two numbers). I do see exactly what you are saying, but it was not the issue. Thanks for attempting to help Shay, I do appreciate it.
Bob Allan
10,900 PointsBob Allan
10,900 PointsOh my gosh, that never crossed my mind! YES! Thank you so much Tobias!