【发布时间】:2011-01-18 19:29:19
【问题描述】:
在一个程序中,我试图检查两个布尔值(从函数返回);需要检查的条件是:
-只有当返回值中的任何一个为真而另一个为假时,我才有问题;
- 否则,如果两者都是对或错,我很高兴进入下一步。
以下两个示例中哪一个是检查条件的有效方法,还是有更好的解决方案?
a 和 b 是整数值,我在 isCorrect 函数中检查条件是否正确,它返回 true 或 false。
1.
// checking for the correctness of both a and b
if ((isCorrect(a) && !isCorrect(b)) ||
(!isCorrect(a) && isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are both correct or incorrect
}
2.
// checking for the correctness of both a and b
if (! (isCorrect(a) ^ isCorrect(b)))
{
// a OR b is incorrect
}
else
{
// a AND b are correct or incorrect
}
谢谢,
伊瓦尔
P.S:代码可读性不是问题。 编辑:我的意思是在第二个选项中有一个 XOR。 另外,我同意 == 和 != 选项,但如果我必须使用布尔运算符怎么办?
【问题讨论】:
-
你的第二个例子好像有错误。
-
@Nikita:确实,右括号。