Infinite loop, don't know how to fix it


#1


https://www.codecademy.com/courses/javascript-beginner-en-ASGIv/2/1?curriculum_id=506324b3a7dffd00020bf661


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.');
    
}


#2

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


#3

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


#4

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


#5

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


#6

not true, inside the loop hello is updated?

hello = Math.random();

#7

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


#8

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