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 Numbers The Math Object Random Number Challenge – Solution

Nelson Jimenez
Nelson Jimenez
3,475 Points

what is wrong with my code?

// Collect input from a user
const maxNumber = parseInt(prompt("Enter a maximum number"));
const minNumber = parseInt(prompt("Enter a minimum number"));

// Convert the input to a number

// Use Math.random() and the user's number to generate a random number
if (maxNumber) {
  const rollDice = Math.round(Math.random() * maxNumber) + minNumber;
  const message = `${rollDice} is a number between ${minNumber} and ${maxNumber}`;
  document.write(message);
} else {
  document.write("You need to enter a number. try again.");
}


// Create a message displaying the random number

1 Answer

Rohald van Merode
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Rohald van Merode
Treehouse Staff

Hey Nelson Jimenez 👋

Looks like the logic for the rollDice variable is a bit off. Currently you're multiplying the random number with the maxNumber and then add the minNumber to the rounded outcome of that. Let's break down what could happen if a user would set the max to be 100 and the min to be 50:

const rollDice = Math.round(Math.random() * 100) + 50;

Math.random() will return a random number from 0 up to but not including 1. For this example let's see what would happen if Math.random returns the number 0.9871:

const rollDice = Math.round(0.9871 * 100) + 50;
// 0.9871 * 100 = 98.71
// Math.round(98.71) = 99
// 99 + 50 = 149

This would result in a 149 dice roll which is outside of the 50-100 bounds set by the user 🙂

Guil goes over a possible solution in the next video if you're interested.

I hope this clears things up and helps you to get going again 😃

Nelson Jimenez
Nelson Jimenez
3,475 Points

thank you for your detailed answer