C++ infinite loop

浪子不回头ぞ 提交于 2019-12-01 13:21:25

问题


I am attempting to write a loop that will repeat until the user enters one of the correct choices (either 1 or 0). For some reason when I have the loop written as below it creates an infinite loop.

I am intending for the loop to only execute while control is not 0 OR not 1, but for some reason it will always execute and becomes an infinite loop.

cout<<"Please enter 1 for another customer or 0 to quit : ";
cin>>control;

  while ((control != 0 )|| (control != 1))
    { 
      cout<<"Invalid Entry! Please enter a 1 to enter another customer or 0 to quit: ";
      cin>>control;
    }

I changed it to be while control less than 0 OR greater than 1, which works but I am still confused as to why the other loop is not working.


回答1:


You have to use && operator.

while ((control != 0 ) && (control != 1))



回答2:


(control != 0) || (control != 1)

is equivalent to,

!(control == 0 && control == 1)

but,

(control == 0 && control == 1) 

is always false (there is no such number).

Therefore, the whole expression will always get true value.




回答3:


The only way to break out

while ((control != 0 )|| (control != 1))

is

!(control != 0) && !(control != 1)

which is equivalent to

control == 0 && control == 1

which is impossible for all integers.



来源:https://stackoverflow.com/questions/19897995/c-infinite-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!