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 trialanalyn jane calado
3,523 Pointswhat a tricky challenge is!! need a comment what's something wrong!
var lowNum = parseInt( prompt('Please enter a number from 1 to 20'));
var highNum = parseInt( prompt('Please enter a number from 100 to 200'));
var randomNum = Math.floor(Math.random() * highNum) + lowNum;
document.write(randomNum);
analyn jane calado
3,523 Pointsah... okie okie.. thanks!!
1 Answer
Rasmus Rønholt
Courses Plus Student 17,358 PointsHey Analyn
Imagine that Math.random() returns something close to 1. Then your result would be higher than highNum. Let me clarify... let's assume the user inputs 20 and 100, and the Math.random() returns 0.9999999999 (you get the idea) then you would end up with a random number of 119.
var lowNum = 20;
var highNum = 100;
var randomNum = Math.floor(0.999999999 * 100) + 20;
To fix this you need to think of the multiplier for Math.random() as a range you want your result to fall within. In this case it would be (and im just typing out the numbers here to make the math easier to understand):
var lowNum = 20;
var highNum = 100;
var validRange = 100 - 20;
var randomNum = Math.floor(0.999999999 * 80) + 20;
The random number above is 79 + 20 = 99, which is valid - but note that it can never be exactly 100. This is because Math.random() never returns 1, and Math.floor rounds everything down. To fix this you need to add 1 to the range. So:
var lowNum = parseInt( prompt('Please enter a number from 1 to 20'));
var highNum = parseInt( prompt('Please enter a number from 100 to 200'));
var validRange = highNum - lowNum + 1
var randomNum = Math.floor(Math.random() * validRange) + lowNum;
Makes sense?
analyn jane calado
3,523 Pointsyeah.. thank you Rasmus for the clarification. ! I'm now satisfied with my answer.
Jimmy Saul
9,851 PointsJimmy Saul
9,851 PointsHi Analyn,
What problem are you experiencing here? It seems to work just fine for me when I copy and paste your code in workspaces.