Welcome to the Treehouse Community
Looking to learn something new?
What is the difference between yours and my ways of getting this task done? Esp I'm interested in the random line.
This is my code:
var firstNum = parseInt(prompt('Type first number')); var secondNum = parseInt(prompt('Type second number')); var dieRoll = Math.floor(Math.random() * secondNum) + firstNum; document.write('<h2>Your random number from ' + firstNum + ' to ' + secondNum +' is ' + dieRoll);
Should I use your variant of formula in code or mine is fine, too?
Math.floor(Math.random() *topNumber-bottomNumber + 1)) + bottomNumber;
Cause my program works completely fine. Is there any use to change mine variant to yours? I thought that +1(firstNum) outside bracket is like max and *secondsNum is like min.
Steven Parker216,164 Points
The formula for producing a random number between two (inclusive) limits is:
random * range + minimum, where "range" is one more than the difference between the two limits. As Phillip pointed out, the operations perfomed by the code shown will potentially produce number larger than the upper limit.
Also, be careful with the placement of parentheses, otherwise the math will be done based on operator precedence, which in this case means the multiply will be done before the addition or subtraction and also throw off the results.