do-while conditions don't stop the loop

后端 未结 2 1664
一整个雨季
一整个雨季 2020-12-04 03:42

I\'ve programmed a Hangman game containing a do-while loop to keep asking the user for letters until they either solved the word or ran out of lives. The weird

相关标签:
2条回答
  • 2020-12-04 04:32
    while(result != 2 || result != -2); 
    

    Lets think about this for a second. If the result is 2 then the right part of the OR is true (result is not equal to -2). And if the result is -2 then the left side of the OR is true (result is not equal to 2).

    0 讨论(0)
  • 2020-12-04 04:37

    Logically, by De Morgan's law,

    result != 2 || result != -2
    

    is the same as

    !(result == 2 && result == -2)
    

    which is always a true expression.


    The condition should probably be

    !(result == complete || result == gameOver)
    

    which, when applying the same law as above, is

    result != complete && result != gameOver
    

    (Using the constants - although I would prefer uppercase symbols like GAMEOVER - instead of the magic numbers also makes the code easier to read.)

    0 讨论(0)
提交回复
热议问题