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 trialSebastian Angelo-Perez
1,835 PointsIs there a mistake in my code or the random challenge has a problem?
I wrote and tried the code. When I chose 1 as starting number (input1) and 3 as a top number (just input) the answer I have is "1 is a number between 1 and 3.". Is there something wrong with my code?
var input1 = prompt("Please type a starting number"); var bottomNumber = parseInt(input1); var input = prompt('Please type a number'); var topNumber = parseInt(input); var randomNumber = Math.floor(Math.random() * (topNumber-bottomNumber + 1)) + bottomNumber ; var message = "<h1>" + randomNumber + " is a number between " + bottomNumber + " and " + topNumber + ".</h1>"; document.write(message);
3 Answers
Jason Anders
Treehouse Moderator 145,860 PointsI ran your code as is and got the #2 and #3 returned a couple of time... #1 did come up most times, but your code is fine and works. If you enter a wider range of numbers, you will notice a significant increase in different numbers coming up.
Jason
Sebastian Angelo-Perez
1,835 PointsThanks Jason, however, what I still don't understand is, why this sentence "1 is a number between 1 and 3." I would have expected any number but #1. It seems that the code is missing something to avoid this mistake, don't you agree? Is it something that one can resolve using conditional statements, perhaps? It will be covered in the next chapter by the way :-).
Jason Anders
Treehouse Moderator 145,860 PointsNo, the code is correct and technically 1 is a number between 1 and 3 (inclusively). The program is a simple one that is designed to show students how to use JavaScript to pick random numbers. If you didn't use the Math.floor method, you would get many many decimal places (e.g. 1.235643234) which is "between" 1 and 3, but Math.floor rounds down to the whole number.
You could code to stop the top and bottom number from being included, but for the purpose of this example, it would just be easier to re-word the sentence to say "From 1 to 3." :)
Sebastian Angelo-Perez
1,835 PointsThanks and yes, you're right, technically 1 is a number between 1 and 3...awesome, now I'm clear and I can move forward!