Search code examples
javascriptif-statementrandomwhile-loopinfinite-loop

Why does Math.floor(Math.random()) function always return "0"?


I am writing a program that chooses a random number between 0 and 1 and then enters a while loop until the random number generator selects a value more than .5. Every time I run the program, the program returns 0 and loops infinitely until it crashes. Why is this occurring? Shouldn't Math.floor(Math.random()) eventually select a number higher than .5?

var randomNumber = Math.floor(Math.random());
while(randomNumber < .5) {
var name = prompt("Do you want to play a game? Like checkers or something?");
if (name === "Yes") {
    console.log("Good jorb!");
} else if(name === "No.") {
    console.log("Go away!!!!!");
 else {
    console.log("I have no idea");
}

var randomNumber = Math.floor(Math.random());
}

Solution

  • This line almost always return 0 and that is why it does not get into the while.

    var randomNumber = Math.floor(Math.random());
    

    Math.random() return float values lower than 1 starting from 0 ... and with Math.floor you are getting the int part which indeed is 0