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

I am having trouble generating a number between the two numbers that were inputted by the user.

The random number is not always a number between the two numbers inputted by the user. I am not sure what I am doing wrong, can anyone provide some help? Thanks.

var userNumber = prompt("Choose a number.");

var userInt = parseInt(userNumber);

var userNumber2 = prompt ("Chose another number.");

var userInt2 = parseInt(userNumber2); 

var randomNumber = Math.floor(Math.random() * (userInt2 - userInt + 1) + userInt2);

var message = randomNumber + " is a number that is between " + userInt + " and " + userInt2;

document.write (message);           

3 Answers

Hi Jennifer,

This is how i would do it:

Ask the user for 2 numbers.

Sort which is bigger.

Put the smallest in a variable num1

Put the largest in a variable num2

Calculate:

var randomNumber = Math.floor(Math.random() * (num2 - num1) + num1);

Using an example, lets say a user types 10 and 5.

num1 is set to 5 and num2 is set to 10 after checking which of the numbers is bigger.

Then you calculate the random number:

(10 - 5) is 5

5*(0 - 0.99) is a number between 0 and 5 - the (0 - 0.99) is the result of the random function

5*(0 - 0.99) + 5 is a number between the 2 numbers the user typed.

Hi Hugo! Thanks for your answer. Follow up: How do you check which of the numbers is bigger?

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Jennifer Hughes

The problem is on this line:

var randomNumber = Math.floor(Math.random() * (userInt2 - userInt + 1) + userInt2);

At the end you should be adding userInt instead of userInt2 like this:

var randomNumber = Math.floor(Math.random() * (userInt2 - userInt + 1) + userInt);

And as a side note, you don't actually need to figure out which number is bigger -- it will work if userInt2 is larger or if userInt is larger -- doesn't matter.