do
{
cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
ch=getch();
} while ( ch !='q' || ch != 'Q');
Why will the code on top not work while the code below does? I tried it with parenthesis around each statement in numerous ways and the compiler would pop an error every time until I regrouped them as I did below. I'm just wondering why it does this.
do
{
cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
ch=getch();
} while ( !(ch=='q' || ch=='Q') );
I'm using Visual Studio 2008 as my compiler; x86 architecture.
(ch != 'q' || ch != 'Q')
is always true: " ch
is not equal to 'q'
or ch
is not equal to 'Q'
".
The problem is your boolean logic is off and the two while
conditions are not the same.
The Top will return true for every single character possible. The bottom will return true for every character except 'q' and 'Q'
I think you want this in your first example:
ch !='q' && ch != 'Q'
You want that the input is not q
AND not Q
.
!(ch=='q' || ch=='Q')
is equivalent to ch!='q' && ch!='Q'
. See also De Morgan's laws .
You've got the logic backwards, that's my negating it works. By DeMirgan's laws, !(ch == 'Q' || ch == 'q')
is the same as ch != 'Q' && ch != 'q'
.
Since a if it cannot be both little q
and big Q
at the same time, while (ch != 'Q' || ch != 'q')
doesn't make sense because if it is 'Q' then it won't be 'q', and vice versa.
When inverting all your logic using ',', you did right by reversing the conditional operators "==" to ".=", but you forgot to reverse the logical operators "||" to "&&": Thus, this should be correct:
while (ch!='q' && ch!='Q');
I use C#, so while code above will work, I would have used this instead as it is easier to read:
while (ch.ToUpper() != 'Q');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.