If statement 如何在if语句中检查两者是否不相等?
我的代码中有很多这样的代码:If statement 如何在if语句中检查两者是否不相等?,if-statement,If Statement,我的代码中有很多这样的代码: if ( x1 == x2 && y1 == y2) { // do nothing } else { // do the thing } 我想知道我是否可以用just if来代替它,而不需要其他东西,以使代码更干净。我尝试了以下方法: if ( x1 != x2 && y1 != y2) { // do the thing } 但这不起作用,因为如果其中只有一个不相等,那么整个事情都是假的。使用德摩根定律
if ( x1 == x2 && y1 == y2) {
// do nothing
}
else {
// do the thing
}
我想知道我是否可以用just if来代替它,而不需要其他东西,以使代码更干净。我尝试了以下方法:
if ( x1 != x2 && y1 != y2) {
// do the thing
}
但这不起作用,因为如果其中只有一个不相等,那么整个事情都是假的。使用德摩根定律(a): 换言之:
if (x1 != x2 || y1 != y2) {
// do the thing
}
如果你不想对命题逻辑考虑太多,你可以使用下面的英语变体
(a) 另一个是:
not (A or B) = (not A) and (not B)
如果您的代码将以If或else语句结尾,那么您可以这样做
if (x1 == x2 && y1 == y2) {
// do something
return; // this will end the execution here.
}
// the else block would be in the rest of execution.
当您试图提交来自用户的特定输入或做出断言时,此方法非常有用。所以我给了你正确的输入,继续执行,否则。。而不是检查不确定的可能性 你试过使用这个吗?:如果(x1!=x2)&&(y1!=y2){//do the thing}@BlitzNinja29:因为关系运算符的优先级高于逻辑比较,所以括号的存在在这里不会有任何影响。嗨@paxdiablo,谢谢你为我解释这个!我有一种强烈的直觉,那就是,如果没有受过正规的计算机科学教育,我很难弄明白这一点。非常感谢。或者,如果你不喜欢学习数学逻辑,你可以在你的条件下编写简单的NOT before of the condition
if(!(x1==x2&&y1==y2))//做smth
@ArthurTarasov这里没有CS-y,你也可以用英语(或任何语言)说:如果不是这个或那个,做点什么。@zlakad实际上我喜欢学习数学逻辑,我完全错过了这个。看那个:!喂,有谁能给我指一个书名,让我可以查到其他类似的东西吗?当我不知道这些东西叫什么的时候,我很难去搜索它们。@ArthurTarasov,搜索一下布尔代数
,这应该是一个很好的起点。
if (x1 == x2 && y1 == y2) {
// do something
return; // this will end the execution here.
}
// the else block would be in the rest of execution.