简体   繁体   English

C ++逻辑运算符Q

[英]C++ logical operator Q

This question might seem very noobish but my question is this: are these two statements logically the same? 这个问题看似很笨拙,但是我的问题是:这两个语句在逻辑上是相同的吗?

int a;
int b;
int c;


if (!a && !b && !c)
//do something



if (!(a || b || c))
//do something

A truth table is useful to understanding logics. 真值表对于理解逻辑很有用。

#include <iostream>

using std::cout;
using std::endl;

int main(void) {
    int a;
    int b;
    int c;
    bool differ = false;

    cout << "a b c x y\n";
    for (a = 0; a <= 1; a++) {
        for (b = 0; b <= 1; b++) {
            for (c = 0; c <= 1; c++) {
                bool x = (!a && !b && !c);
                bool y =  (!(a || b || c));
                differ = differ || (x != y);
                cout << a << " " << b << " " << c << " " << x << " " << y << "\n";
            }
        }
    }
    if (differ) {
        cout << "they differ" << endl;
    } else {
        cout << "they are the same" << endl;
    }
    return 0;
}

Actually they are the same thanks to De Morgan's laws: 实际上,由于De Morgan的定律,它们是相同的:

  !a && !b && !c
= !(a || b) && !c
= !((a || b) || c)
= !(a || b || c)

( = here is not the C++ assignment operator) =这里不是C ++赋值运算符)

No. On your first statement, all conditions must be met. 否。在您的第一个声明中,必须满足所有条件。 && operator means All should be true to make the result true otherwise it would be false. &&运算符的意思是All应该为true以使结果为true,否则为false。 On your second statement, If one or more condition is true, then the condition would be done. 在第二条语句中,如果一个或多个条件为真,则该条件将完成。

Sorry for a very brief explanation. 抱歉,非常简短的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM