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

Random 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.

//Fixed Code Presentation

3 Answers

Brendan- 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); 

not sure why it came out like that...I wrapped it in the backticks :(

//Fixed Code Presentation

How to post Code

Thanks 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?

I confirmed it. The problem was I wasn't using parseInt on the initial input strings. Everything else I had seems fine.

Thanks again.