samedi 10 juillet 2021

Why does generating a random number outside of a loop, causes it to be always the same?

When I create a random number inside a while loop as a local variable everything works, but when I generate a random number as a global variable then I get stuck in an infinite loop.
I don't understand how and why this should make any difference. Goal is to output all the random numbers that are less than 0.7 with a While Loop.

Here is the code that creates an infinite loop:

let rnd = Math.random();
let continue = true;

while (continue) {
  console.log(rnd);
  if (rnd > 0.7) {
    continue = false;
    alert(rnd + ' is bigger than 0.7!');
  }
}

Here is the code that works (only thing that is changed is that the random number is generated within the while loop).

let continue = true;

while (continue) {
  let rnd = Math.random();
  console.log(rnd);
  if (rnd > 0.7) {
    continue = false;
    alert(rnd + ' is bigger than 0.7!');
  }
}

I'm not interested in creating this with another kind of loop, I'm just trying to understand the While Loop better.




Aucun commentaire:

Enregistrer un commentaire