我正在读一本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
Run Code Online (Sandbox Code Playgroud)
答案是对的.
其他几个答案都说括号确定了评估顺序.那是错的.在C中,优先级与评估顺序不同.优先级确定哪些操作数由哪些运算符分组.评估的确切顺序未指定.逻辑运算符是一个例外:它们以严格从左到右的顺序进行评估,以便实现短路行为.