JavaScript JavaScript Numbers The Math Object Random Number Challenge – Two Numbers Solution

Is the below solution correct as well? It seems to work fine for me.

// Collect input from a user const lowUserInput = parseInt ( prompt("Please enter your first number.") ); const highUserInput = parseInt ( prompt("Please enter your second number.") );

// Convert the input to a number

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

// Create a message displaying the random number alert(${randomNumber} is between ${lowUserInput} and ${highUserInput});

// Create a message displaying the random number } else { console.log(Please enter a valid number.) }

Tai Jun Jie
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tai Jun Jie
Full Stack JavaScript Techdegree Graduate 23,907 Points

Hey, the solution below is incorrect.

randomNumber = Math.floor ( Math.random() * highUserInput ) + lowUserInput;

there is just 1 problem with this code. This code above would return a max number of (highest input + lowest input) instead of just the highest input. In order to fix this, you can see the code below

randomNumber = Math.floor ( Math.random() * (highUserInput-lowestUserInput + 1) ) + lowUserInput;

As you can see, you need to minus the lowUserInput from ( Math.random() * (highUserInput-lowUserInput + 1) . You add 1 in order to include the lowUserInput and the highUserInput in the range.

For more info, you can use this link. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

2 Answers

Steven Parker
Steven Parker
207,602 Points

As already pointed out, the formula to create a number within a range is not correct.

Finding issues like this often requires be clever about the test scenarios, as simple examples might seem to be working. For this case, try using this formula to get a few samples of numbers between 90 and 99.

Also, using the && operator by itself isn't an effective way to test numbers for validity (the "isNaN" function can be useful). Try testing the current code by asking for a number between 0 and 9.

Thank you guys!