2016-04-28 64 views
0

我在代码中看到了逻辑和比较操作,我觉得它可以被简化。如何确保两个逻辑和比较操作相等?

简单地说,它看起来像:

if (!a || !(b || c)) {...} 

但我认为这是一样

if (!a || !b || !c) {...} 

我应该如何在这种情况下怎么办?我想我可以在现有的代码中看到更多这样的操作。除了手动检查外,是否有规则来简化/优化这种操作?

+0

有趣的链接:[德摩根法](https://en.wikipedia.org/wiki/De_Morgan's_laws) – DenseCrab

+0

https://en.wikipedia.org/wiki/De_Morgan's_laws您的转型应该引入了'&&'某处:“不(A或B)”与“(不是A)和(不是B)”相同。 – Thilo

回答

1

您可以申请DeMorgan's law获得:

if (!a || (!b && !c)) {...} 

其中,由于具有比||更高的优先级&&,是一样的:

if (!a || !b && !c) {...} 

不过是整个环境显得非常不利,并阅读正面条件几乎总是比较容易,可能写得更好:

// This is the negation of your condition after applying DeMorgan's law 
if (a && (b || c)) { 
    // return or throw error 
} 

... // What you would've done in the if statement 
0

问题是如果!(b || c)我们和!b ||一样!C。 尝试一个简单的道理表:

b c !(b||c) !b||!c 
0 0 1   1 
0 1 0   1 
1 0 0   1 
1 1 0   0 

因此,他们是不一样的。

0

对于接近这种类型的布尔重构的,如果你不相信自己的能力,构建真值表一般的技术,怎么样沿着这些线路写一些代码:

for a in {true, false} 
    for b in {true, false} 
    for c in {true, false} 
     if (!a || !(b || c)) <> (!a || !b || !c) 
     then exit with message "Not equivalent" 
    end 
    end 
end 

if条件可当然可以用您试图测试的任何两个表达式替换。