我是编程新手,我需要在 if 条件中验证几个表达式,当它们都返回 true 时,只需要做一些工作。
我知道我可以通过使用逻辑运算符来做到这一点,但我不清楚逻辑运算符是如何工作的。
对此的任何帮助将不胜感激。
提前谢谢。
最好使用逻辑运算符,多个条件。
例如
int firstValue=10; int sencondValue=16;
// OR operator , retursn TRUE is any of given condtion is true.
if (firstValue==10 || sencondValue==13 || firstValue>=5) {
NSLog(@"True");
}
else
{
NSLog(@"False");
}
//above are 3 condtions in one statement , if any condition is true , result is true
// AND operator , retursn TRUE is all of given condtion are true and flase if any on the given conditions are false.
if (firstValue==10 && sencondValue==13 && firstValue>=5) {
NSLog(@"True");
}
else
{
NSLog(@"False");
}
与许多编程语言一样,有可用的逻辑运算符。
您似乎正在寻找AND
运算符:
if (conditionA && conditionB) {
// conditional code
}
有关更多信息,请参阅维基百科:C 中的逻辑运算符。
使用短路逻辑和运算符...
例 1.
if (1 == 1 && 2 == 2) {
// statements that will always execute
}
例 2
boolean firstCondition = YES;
boolean secondCondition = NO;
boolean thirdCondition = YES;
if (firstCondition && secondCondition && thirdCondition) {
// As secondCondition is false this will never execute (and thirdCondition will never be evaluated)
}
使用逻辑和运算符,大括号中的语句仅在第一个和第二个条件的计算结果为 true 时执行。 此外,如果第一个条件为假,则甚至不会评估第二个条件,因此称为短路。