I am using
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?
<html>
<head>
<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 reply = "";
var msg = "";
var high = 100;
var low = 1;
msg = "Please think of a number between 1 and 100. \
";
msg += "I will try to guess the number you thought.
";
msg += "If the number I guess is too high please reply with a ‘h’.
";
msg += "If the number I guess is too low please reply with a ‘l’.
";
msg += "If I guess correctly please reply with a ‘c’.
";
alert(msg);
while(reply != 'c'){
guess = Math.floor(Math.random() * high) + low;
alert("low: "+low); //testing statement
alert("high: "+high); //testing statement
//alert("guess: "+guess); //testing statement
msg = "My guess is: "+guess+". \
";
msg += “Please reply with h=high/l=low/c=correct.
“;
reply = prompt(msg,””);
if(reply == 'h'){
high = guess;
} //too high condition
if(reply == 'l'){
low = guess;
} //too low condition
if(reply == 'c'){
alert("Hooray!!! I am the greatest guesser.");
} //correct guess condition
} //end while loop
</script>
</head>
<body>
<center>
<h2>The Number Guessing Game</h2>
</center>
<hr>
<h3>Please refresh the page to play the game again.</h3>
</body>
</html>