Jac*_*You 3 boolean-logic boolean-expression boolean-operations
在我的Be Prepared Comp Sci 教科书中,我遇到了这个问题:
假设 x、y 和 z 是整数变量,以下三个逻辑表达式中哪一个是等价的,即对于 x、y 和 z 的所有可能值具有相等的值?
(x == y && x != z) || (x != y && x == z)
(x == y || x == z) && (x != y || x != z)
(x == y) != (x == z)
A. None of the three
B. I and II only
C. II and III only
D. I and III only
E. I, II, and III
Run Code Online (Sandbox Code Playgroud)
我选择了“B”,但弄错了。我真的认为我需要帮助理解布尔逻辑。正确答案说的是别的,但我不明白逻辑。以下是正确答案:
表达式 III 是答案的关键:所有三个表达式都说明了两个等式中的一个(x == y 或 x == z)为真的事实。
表达式 I 声明第一个而不是第二个或第二个而不是第一个是真的。
表达式 II 表示两者之一为真,两者之一为假。
表达式 III 只是说明它们具有不同的值。这三个归结为同一件事。答案是E。
(x == y && x != z) || (x != y && x == z)
(x == y || x == z) && (x != y || x != z)
(x == y) != (x == z)
Run Code Online (Sandbox Code Playgroud)
让我们分解这些。
(x == y && x != z) || (x != y && x == z)
x is equal to y and not z, or x is equal to z and not y
Run Code Online (Sandbox Code Playgroud)
所以基本上,x is equal to one of [y|z], but y != z
。
(x == y || x == z) && (x != y || x != z)
x is equal to y or x is equal to z, and x is not equal to y or x is not equal to z
Run Code Online (Sandbox Code Playgroud)
这有点复杂。它几乎归结为x equals one of [y|z] but not the other
, 或x is equal to y and not z, or x is equal to z and not y
,与第一个方程相同。
这是因为(x == y)
会使方程的前半部分成立,但因此x != y
在后半部分肯定是错误的。因此,为了使等式的后半部分保持正确,x 必须不等于 z。如果你愿意,你可以翻转这个逻辑来表示 x == z 但 x != y。如上所述,这归结为x is equal to one of [y|z] but not the other
.
(x == y) != (x == z)
The value of the expression x == y is the opposite of the value of the expression x == z.
Run Code Online (Sandbox Code Playgroud)
这也有点复杂,但它适用于同一件事。如果 x 等于 y,为了保持语句正确,x 必须不等于 z。反之,如果X不等于Y,X必须等于ž。因此,x is equal to one of [y|z] but not the other
。