if ((A && B) || (!A)) // or simplified to (!A || B) as suggested in comments
{
do C
}
否则,将“ C”的代码放在一个单独的函数中,并调用:
DoActionC()
{
....
// code for Action C
}
if (condition A)
{
if(condition B)
{
DoActionC(); // call the function
}
else
...
}
else
{
DoActionC(); // call the function
}
重新排列您的逻辑,这样您就不会有那么多嵌套的 if 语句。问问自己是什么条件导致了“行动 C”的发生。在我看来,当“条件 B”为真或“条件 A”为假时,就会发生这种情况。我们可以把它写成“非 A 或 B”。把这个转换成 C 代码,我们得到
if (!A || B) {
action C
} else {
...
}
To learn more about these kind of expressions, I suggest googling "boolean algebra", "predicate logic", and "predicate calculus". These are deep mathematical topics. You don't need to learn it all, just the basics.
You should also learn about "short circuit evaluation". Because of this, the order of the expressions is important to exactly duplicate your original logic. While B || !A is logically equivalent, using this as the condition will execute "action C" when B is true regardless of the value of A.
首先要做的是查看,在什么条件下要执行 C。这就是 (a & b)。也是当 !a。
所以你有 (a & b) | !a。
如果你想最小化,你可以继续,就像“正常”的算术一样,你可以乘出。
(a & b) | !a = (a | !a) & (b | !a).
啊!A 总是为真,因此可以将其删除,这样就得到了最小化的结果: b | !a。
如果顺序有所不同,因为您想要检查 b 只有当!A 为真(例如当!A 是一个空指针检查,b 是一个对指针的操作,就像@Lord Farquaad 在他的评论中指出的那样) ,你可能需要切换这两个。
另一种情况(/* ... */)将始终在没有执行 c 时执行,所以我们可以将其放在 else 情况中。
同样值得一提的是,无论采用哪种方式,将操作 c 放入方法中都可能是有意义的。
剩下的代码如下:
if (!A || B)
{
doActionC() // execute method which does action C
}
else
{
/* ... */ // what ever happens here, you might want to put it into a method, too.
}
bool do_action_C;
// Determine whether we need to do action C or just do the "..." action
// If condition A is matched, condition B needs to be matched in order to do action C
if (/* condition A */)
{
if(/* condition B */)
do_action_C = true; // have to do action C because blah
else
do_action_C = false; // no need to do action C because blarg
}
else
{
do_action_C = true; // A is false, so obviously have to do action C
}
if (do_action_C)
{
DoActionC(); // call the function
}
else
{
...
}