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 trialBrendan Colledanchise
6,688 PointsRandom Challenge - What is wrong with my second part?
Hello,
I managed to get the first part of the challenge done. This generates a random number from 1 to the specified number given by the user. Here is my code (it is commented out):
var userRandomNumber = prompt("Give me a number");
var generatedNumber = Math.random() * (userRandomNumber) + 1;
document.write(parseInt(generatedNumber));
Here is what I have for the second part of the challenge. This is supposed to generate a random number between a specified range given by the user:
var userRandomNumberFirst = prompt("Give me a number");
var userRandomNumberSecond = prompt("Give me a larger number");
var generatedNumber = Math.floor(Math.random() * (userRandomNumberSecond - userRandomNumberFirst + 1)) + userRandomNumberFirst;
document.write(parseInt(generatedNumber));
This isn't working. For example, it might generate 41 for between 1 and 5.
How do I solve this? Thanks for your help.
3 Answers
Kathleen Sapp
12,776 PointsBrendan- This is the code I used and it works. Give it a try.
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 = "<p>" + randomNumber + " is a number between " + bottomNumber + " and " + topNumber + ".</p>";
document.write(message);
Kathleen Sapp
12,776 Pointsnot sure why it came out like that...I wrapped it in the backticks :(
Chyno Deluxe
16,936 Points//Fixed Code Presentation
How to post Code
Brendan Colledanchise
6,688 PointsThanks for your response. I tested it out and it works.
What was wrong with my code? I compared ours, and I couldn't find what was wrong with mine. Does it have to do with using parseInt earlier?
Brendan Colledanchise
6,688 PointsI confirmed it. The problem was I wasn't using parseInt on the initial input strings. Everything else I had seems fine.
Thanks again.
Chyno Deluxe
16,936 PointsChyno Deluxe
16,936 Points//Fixed Code Presentation