如何在这个C 逻辑运算中应用DeMorgan 定律?

How to apply DeMorgan's law in this C logical operation?

我想比较三个值是否唯一,这是我的第一个陈述,我想使用德摩根定律对其进行简化并使其更具可读性。

product1Id != product2Id && product1Id != product3Id

I want to compare three values if they're unique or not,

您的代码无法确保这一点。 C(3,2) = 3!/2!/(3-2)! = 需要 3 次比较,但你只有两次。以下是正确的检查:

product1Id != product2Id &&
product1Id != product3Id &&
product2Id != product3Id

I want to simplify and make it more readable

德摩根定律可用于获得

!( product1Id == product2Id || product1Id == product3Id )

(请参阅下面的几种方法。)

这是否更具可读性值得商榷。

但也许 !( ) 可以通过交换 if 语句的“then”和“else”子句来省略,将表达式简化为

product1Id == product2Id || product1Id == product3Id

此外,假设您必须使用 product1Id 的不同值重复进行此检查,并假设您有大量产品 ID 需要检查。然后可以使用

// Setup
ProductSet *set = ProductSet_new();
ProductSet_add( set, product2Id );
ProductSet_add( set, product3Id );

!( ProductSet_has( set, product1Id ) )

How to apply DeMorgan's law in this C logical operation?

方法一:从!( A && B )!( A || B )

开始

让我们开始通过引入一个double-negation来合成这个形式。

!( !( product1Id != product2Id && product1Id != product3Id ) )
      |----------A-----------|    |----------B-----------|
   |----------------------!( A && B )----------------------|

现在,我们可以应用德摩根第二定律 (!( A && B )!A || !B)。

   |--------------------------!A || !B--------------------------|
   |------------!A-------------|    |------------!B-------------|
      |----------A-----------|         |----------B-----------|
!( !( product1Id != product2Id ) || !( product1Id != product3Id ) )

让我们使用 A == B!( A != B ).

来简化
!( product1Id == product2Id || product1Id == product3Id )

方法 2a:从 !A && !B!A || !B

开始

让我们开始通过引入double-negations来综合这个形式。

!( !( product1Id != product2Id ) ) && !( !( product1Id != product3Id ) )
   |-------------A-------------|         |-------------B-------------|
|---------------!A---------------|    |---------------!B---------------|
|-------------------------------!A && !B-------------------------------|

现在,我们可以应用德摩根第一定律(!( A || B )!A && !B)。

|---------------------------!( A || B )---------------------------|
   |---------------------------A || B---------------------------|
   |-------------A-------------|    |-------------B-------------|
!( !( product1Id != product2Id ) || !( product1Id != product3Id ) )

让我们使用 !( A != B )A == B.

来简化
!( product1Id == product2Id || product1Id == product3Id )

方法 2b:从 !A && !B!A || !B

开始

让我们从使用 A != B!( A == B ).

合成这个表格开始
!( product1Id == product2Id ) && !( product1Id == product3Id )
   |----------A-----------|         |----------B-----------|
|------------!A-------------|    |------------!B-------------|
|--------------------------!A && !B --------------------------|

现在,我们可以应用德摩根第一定律(!( A || B )!A && !B)。

|----------------------!( A || B )----------------------|
   |----------------------A || B----------------------|
   |----------A-----------|    |----------B-----------|
!( product1Id == product2Id || product1Id == product3Id )