# Random Number Generation.

• Jul 6, 2010, 08:40
johnny_dipin
Random Number Generation.
I am using

Quote:

Math.floor(Math.random() * high) + low;
to generate a random number. I thought this will generate a random value between the high value and low value. But when I use it in the below program the number generated is sometimes greater than the high value. Can someone please tell me why?

Quote:

<html>
<title>The Number Guessing Game</title>
<script>
//Dipin
//The Number Guessing Game
//The computer will the guess the number that the use thinks

var guess = 0;
var msg = "";
var high = 100;
var low = 1;

msg = "Please think of a number between 1 and 100. \n";
msg += "I will try to guess the number you thought. \n";
msg += "If the number I guess is too high please reply with a 'h'. \n";
msg += "If the number I guess is too low please reply with a 'l'. \n";
msg += "If I guess correctly please reply with a 'c'. \n";

guess = Math.floor(Math.random() * high) + low;

msg = "My guess is: "+guess+". \n";

high = guess;
} //too high condition
low = guess;
} //too low condition
alert("Hooray!!! I am the greatest guesser.");
} //correct guess condition
} //end while loop
</script>
<body>
<center>
<h2>The Number Guessing Game</h2>
</center>
<hr>
<h3>Please refresh the page to play the game again.</h3>
</body>
</html>

• Jul 6, 2010, 08:56
siteguru
Code:

```var range = high - low; var rndnum = Math.floor(Math.random() * range) + low;```
• Jul 6, 2010, 09:07
johnny_dipin
Thank you. That seems to work perfectly.
• Jul 6, 2010, 13:07
r51
Quote:

Originally Posted by siteguru
Code:

```var range = high - low; var rndnum = Math.floor(Math.random() * range) + low;```

Notice that the code gives a number from low to high but not including high. For example, if low is 1 and high is 10, it will give random whole numbers from 1 to 9 inclusive. 10 is not included.
• Jul 6, 2010, 14:33
felgall
If you want it to include high as one of the values then simply use

var range = high - low + 1;