Infinite loop, don't know how to fix it


Every time I run the code, I get an infinite loop, I don't know how to fix it. This is my code:

hello = Math.random();

while (hello != 0.5) {
    hello = Math.random();
    console.log('Sorry, try again.');


the while loop will as long as the condition is true. Which means Math.random() has to be exactly 0.5 to make it stop, small change


In that case, is impossible to make a while with Math.random();?


no, it is not impossible. you could do something like this for example:

while (hello < 0.5)

no, while hello is smaller then 0.5, keep running. That is a 50% change. you could also do < 0.33 or something, a 1/3 change.

but the change that the number becomes 0.5 with so many decimal numbers, is like very small. Or you could round the random number to one digit, then you could do it, since it is a 1/10 change


also, the math.random is only executed once, so if the statement is true, then it stays true, making it an infinite loop!


not true, inside the loop hello is updated?

hello = Math.random();


oh yeah! :open_mouth:
sorry didn't see that


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.