3

I am reading a C book and don't understand a statement it is asking me to evaluate.

Here is the statement, !(1 && !(0 || 1))

I can understand some things here... This is what I have so far, not(1 and not(0 or 1))

So it's not 1 and not 0 or 1? Or is it not 1 and 0 or 1? Do those two ! cancel each other out like a double negative? The answer is true but I expected false.

Can someone explain?

4

11 回答 11

5

使用德摩根定律简化原来的表达式:!(1 && !(0 || 1))。当您对带括号的逻辑表达式求反时,对每个操作数都应用取反并更改运算符。

!(1 && !(0 || 1))   // original expression
!1 || !!(O || 1)    // by De Morgan's law
!1 || (0 || 1)      // the two !!'s in front of the second operand cancel each other
0 || (0 || 1)       // !1 is zero
0 || 1              // the second operand, 0 || 1, evaluates to true because 1 is true
1                   // the entire expression is now 0 || 1, which is true

答案是真的。

其他几个答案说括号决定了评估的顺序。那是错的。在 C 中,优先级与评估顺序不同。优先级决定了哪些操作数由哪些运算符分组。评估的确切顺序未指定。逻辑运算符是一个例外:它们严格按照从左到右的顺序进行评估,以启用短路行为。

于 2013-08-13T04:46:27.997 回答
3
  1. (0 || 1) == 1
  2. !1 == 0
  3. 1 && 0 == 0
  4. !0 == 1也称为真 :)

请记住,||and&&是短路运算符,但在这种情况下,您仍然需要评估右侧,因为运算符不会短路

于 2013-08-13T04:24:03.260 回答
3
!(1 && !(0 || 1))           =>     not(1 and not(0 or 1))
not(1 and not(0 or 1))      =>     not(1 and (0 and 1))      // !(a or b) = a and b
not(1 and (0 and 1))        =>     not(0)    =>  1  =>  true
于 2013-08-13T04:33:10.193 回答
2
   !(1 && !(0 || 1))
=> ! (1 && !(1))     //0 || 1 is 1
=> ! (1 && 0)        // !1 is 0
=> !0                // 1 && 0 is 0
=> 1                 // !0 is 1
=>true
于 2013-08-13T04:24:53.667 回答
2

如果 A =1 A && B = B。所以 !(....) 中的最终表达式是 !(!(0 || 1)) ,即 0 || 1 和 0 + 1 =1 因此答案是正确的

于 2013-08-13T04:26:27.170 回答
2
!(1 && !(0 || 1))  =>  !(1 && !(1)) =>  !(1 && !1)  => !(1 && 0) => !(0) => !0 => 1(true) 
于 2013-08-13T05:02:51.100 回答
1

从最深的嵌套开始,逐步向外添加;

(0 || 1) = (0 OR 1) = 1

!(0 || 1) = !1 = NOT 1 = 0

1 && !(0 || 1) = 1 && 0 = 1 AND 0 = 0

!(1 && !(0 || 1)) = !0 = NOT 0 = 1
于 2013-08-13T04:24:46.657 回答
1

要对此进行评估,请从最里面的括号开始,然后按如下方式解决:

not(1 and not(0 or 1)) -> not(1 and not(1)) -> not(1 and 0) -> not(0) -> 1 -> true.
于 2013-08-13T04:24:58.310 回答
1
!(1 && !(0 || 1))

由于0 || 1评估为1,与

!(1 && !1)

继续

!(1 && 0)

继续

!0

原来如此1,真的。

于 2013-08-13T04:25:28.433 回答
1
(0 || 1) --> 1

! 1      --> 0

1 && 0   --> 0

! 0     -- > 1

回答正确

于 2013-08-13T04:25:29.000 回答
1

如果您记得哪个操作顺序很容易

 !(1 && !(0 || 1)) = !(1 && !(1)) = !(1 && 0) = !(0) = 1
于 2013-08-13T04:26:15.863 回答