Or and not equal

前端 未结 6 683
忘掉有多难
忘掉有多难 2021-01-24 20:23

Why does this work?

#include 
#include 
using namespace std;
int main(){
string s=\"a\";
if((s==\"cm\")||(s==\"in\")||(s==\"ft\")||         


        
相关标签:
6条回答
  • 2021-01-24 21:00

    Negation changes the logic behind it. There's more theory here http://en.wikipedia.org/wiki/Negation but basically, in the second example, you want to check that none of the conditions match - meaning you'd have to have && (and) operator instead of || (or)

    0 讨论(0)
  • 2021-01-24 21:04
    (s!="cm")||(s!="in")||(s!="ft")||(s!="m")
    

    Each and everyone of those is true, so clearly the expression is true.

    0 讨论(0)
  • You're trying to check whether it's unequal to all of those strings, not whether it's unequal to any of those strings.

    Use and, not or.

    0 讨论(0)
  • 2021-01-24 21:07

    In your second case s != "cm" and of course the first cout is printed. To negate the check and the logic to remain the same, do it like this:

    if((s!="cm")&&(s!="in")&&(s!="ft")&&(s!="m"))
            cout<<"I like "+s;
    else
            cout<<s+" Is an illegal value";
    
    0 讨论(0)
  • 2021-01-24 21:07

    More specifically, you didn't apply De Morgan's law correctly: http://en.wikipedia.org/wiki/De_Morgan%27s_laws.

    0 讨论(0)
  • 2021-01-24 21:19

    Why should the second one output "I like a"? Every single one of your conditions in the statement in the second example is true, so it goes into the if branch. Even if only one would be true, it still would go into the if branch, because you are using OR.

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