簡體   English   中英

評價本聲明

[英]Evaluation of this statement

我正在讀一本C書而且不理解它要求我評估的聲明。

這是聲明, !(1 && !(0 || 1))

我可以在這里理解一些事情......這是我到目前為止所做的事情, not(1 and not(0 or 1))

所以它not 1 and not 0 or 1 或者它not 1 and 0 or 1 做那兩個! 像雙重否定一樣取消對方? 答案是true但我的預期是false

誰能解釋一下?

使用De Morgan定律簡化原始表達式: !(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中,優先級與評估順序不同。 優先級確定哪些操作數由哪些運算符分組。 評估的確切順序未指定。 邏輯運算符是一個例外:它們以嚴格從左到右的順序進行評估,以便實現短路行為。

  1. (0 || 1) == 1
  2. !1 == 0
  3. 1 && 0 == 0
  4. !0 == 1也稱為真:)

請記住|| &&是短路運算符,但在這種情況下,您仍需要評估右側,因為運算符不會短路

!(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
   !(1 && !(0 || 1))
=> ! (1 && !(1))     //0 || 1 is 1
=> ! (1 && 0)        // !1 is 0
=> !0                // 1 && 0 is 0
=> 1                 // !0 is 1
=>true

如果A = 1 A && B = B.那么內部的最終表達式!(....)是!(!(0 || 1))是0 || 1和0 + 1 = 1因此答案是真的

!(1 && !(0 || 1))  =>  !(1 && !(1)) =>  !(1 && !1)  => !(1 && 0) => !(0) => !0 => 1(true) 

從最深的築巢和向外工作開始逐個添加;

(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

要評估這一點,請從最里面的括號開始,然后按照這樣的方式解決問題:

not(1 and not(0 or 1)) -> not(1 and not(1)) -> not(1 and 0) -> not(0) -> 1 -> true.
!(1 && !(0 || 1))

因為0 || 1 0 || 1評估為1 ,與...相同

!(1 && !1)

繼續

!(1 && 0)

繼續

!0

所以這是1 ,真實。

(0 || 1) --> 1

! 1      --> 0

1 && 0   --> 0

! 0     -- > 1

回答是真的

如果您記得哪個操作訂單很容易

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM