[英]Why am I getting a division by zero error here?
I'm getting a division by zero error on this line of code: 我在这行代码中得到零除错误:
$ratio['p{W}'] = ($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0) ? 0 : ($ratio['{W}'] / $colorTotal) * 100;
I've tested the above with: 我用以下方法测试了上面的内容:
echo '$ratio[{W}]:'.$ratio['{W}'].', $colorTotal:'.$colorTotal;
if($ratio['{W}'] === 0) {
echo('$ratio[{W}]: zero');
}
else {
echo('$ratio[{W}]: not zero');
}
if($colorTotal === 0) {
echo('$colorTotal: zero');
}
else {
echo('$colorTotal: not zero');
}
and the results are: 结果是:
[01-Jul-2015 17:40:26 UTC] $ratio[{W}]:0, $colorTotal:0
[01-Jul-2015 17:40:26 UTC] $ratio[{W}]: zero
[01-Jul-2015 17:40:26 UTC] $colorTotal: zero
It seems I should never reach this point ( $ratio['{W}'] / $colorTotal
) in the code since the previous criteria is 0 in the checks but it seems to reach it? 似乎我永远都不会在代码中达到这一点(
$ratio['{W}'] / $colorTotal
),因为先前的条件在检查中为0,但似乎达到了? How can I prevent this error? 如何防止此错误?
Ternary operators are left-associative in PHP. 三元运算符在PHP中是左关联的。 Your code is equivalent to:
您的代码等效于:
$ratio['p{W}'] = (($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0)) ? 0 : ($ratio['{W}'] / $colorTotal) * 100;
meaning that ($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0)
表示
($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0)
($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0)
evaluates first. ($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0)
首先求值。 The result of this is either 0
or true
, meaning that the true part of the second ternary will always execute. 其结果为
0
或true
,这意味着将始终执行第二个三进制数的真实部分。
It looks to me like you probably want to make the whole expression right-associative: 在我看来,您可能想使整个表达式正确关联:
$ratio['p{W}'] = ($ratio['{W}'] === 0) ? 0 : (($colorTotal === 0) ? 0 : ($ratio['{W}'] / $colorTotal) * 100);
I'll start out by adding parenthesis around your ternaries, since I'm afraid ElGavilan is right. 首先,我会在您的三进制周围添加括号,因为恐怕ElGavilan是正确的。 Your one-liner is quite ugly to read, and refers to code we don't have, which means we can't test your code.
您的单行代码很难读,并且引用了我们没有的代码,这意味着我们无法测试您的代码。
I like ternaries... but not that way ! 我喜欢三元...但是不是那样!
$ratio['p{W}'] = ($ratio['{W}'] === 0) ? 0 : ($colorTotal === 0) ? 0 : ($ratio['{W}'] / $colorTotal) * 100;
($ratio['{W}'] === 0)
表示$ratio['{W}']
为假,然后在两种情况下都执行错误代码($colorTotal === 0)
($ratio['{W}'] === 0) & ($colorTotal === 0)
值变为0。与最后一个案例除法案例0/0相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.