表达式“a and b or not a and c”的方法差异
Difference in approaches for the expression `a and b or not a and c`
我想设置一个布尔变量,该变量应该对 (a && b) || (!a && c)
为真。
我的第一个想法是简单地把它写下来:
$result = ($a && $b) || (!$a && $c);
但是这样做会不会更好或更省时:
$result = false;
if ( $a ) {
$result = $b;
} else {
$result = $c;
}
此处您要检查两者是否为真或 a
为假且 c
为真:
($a && $b) || (!$a && $c);
这边:
$result = false;
if ( $a ) {
$result = $b;
} else {
$result = $c;
}
如果 a
为假,则输出 c
否则 b
你到底想做什么?
您必须寻找三元运算符:($a) ? $b : $c;
查看详细解释:http://www.abeautifulsite.net/how-to-use-the-php-ternary-operator/
尝试如下:
$result = ($a==true)?$b;$c
这个:
$result = false; /* this line has no usefulness */
if ( $a ) {
$result = $b;
} else {
$result = $c;
}
只是更冗长的版本:
$result = $a ? $b : $c;
但两者会略有不同:
$result = ($a && $b) || (!$a && $c);
if $a
是有副作用的东西,因为它可能在这段代码中被评估两次。
使用现代 CPU,你获得的时间比写这个问题的时间要少,即使在 1000000 次执行中,无论如何
如果要分配结果:
result=a?b:c;
如果你想检查一个 if/while:
if(a?b:c){
...
}
我想设置一个布尔变量,该变量应该对 (a && b) || (!a && c)
为真。
我的第一个想法是简单地把它写下来:
$result = ($a && $b) || (!$a && $c);
但是这样做会不会更好或更省时:
$result = false;
if ( $a ) {
$result = $b;
} else {
$result = $c;
}
此处您要检查两者是否为真或 a
为假且 c
为真:
($a && $b) || (!$a && $c);
这边:
$result = false;
if ( $a ) {
$result = $b;
} else {
$result = $c;
}
如果 a
为假,则输出 c
否则 b
你到底想做什么?
您必须寻找三元运算符:($a) ? $b : $c;
查看详细解释:http://www.abeautifulsite.net/how-to-use-the-php-ternary-operator/
尝试如下:
$result = ($a==true)?$b;$c
这个:
$result = false; /* this line has no usefulness */
if ( $a ) {
$result = $b;
} else {
$result = $c;
}
只是更冗长的版本:
$result = $a ? $b : $c;
但两者会略有不同:
$result = ($a && $b) || (!$a && $c);
if $a
是有副作用的东西,因为它可能在这段代码中被评估两次。
使用现代 CPU,你获得的时间比写这个问题的时间要少,即使在 1000000 次执行中,无论如何
如果要分配结果:
result=a?b:c;
如果你想检查一个 if/while:
if(a?b:c){
...
}