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

Andy Hyman
Andy Hyman
5,238 Points

Equation not inclusive of lowest number?

My solution is pretty much exactly the same as the video solution. However, when entering two numbers, the random number generated never seems to include the low number, for example even if I entered 10 and 13, the output would always be 11, 12 or 13 but never 10? Have I done something wrong?

I have also tried adding 0.5 instead of 1 which seems to fix the problem but not sure if this is correct, Maths isn't my forte so any help would be appreciated!

Thanks

// Collect input from a user
const userInputLow = prompt("Please enter your lowest number");
const userInputHigh = prompt("Please enter your highest number");

// Convert the input to a number

const userNumberLow = parseInt(userInputLow);
const userNumberHigh = parseInt(userInputHigh);

if (userNumberLow && userNumberHigh) {
  // Use Math.random() and the user's number to generate a random number
  const randomNumber = Math.floor(Math.random() * (userNumberHigh -userNumberLow) + 1) + userNumberLow;

  console.log(`${randomNumber} is a number between ${userNumberLow} and  ${userNumberHigh}.`);

} else {
  console.log("This is not a number, please try again.");
}

1 Answer

Steven Parker
Steven Parker
231,141 Points

The " + 1 " should be done inside the parentheses to compute the range before multiplying. Adding it after does exactly what you observed and makes the range exclusive of the lower number.

Also, "if (userNumberLow && userNumberHigh)" is not an effective test for number validity. Try asking for a number between 0 and 9. :see_no_evil: You'll probably want to make use of the "isNaN" function.

And when posting code to the forum, use Markdown formatting to preserve the appearance, and optionally add syntax coloring.