简体   繁体   中英

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? How can I prevent this error?

Ternary operators are left-associative in 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) evaluates first. The result of this is either 0 or true , meaning that the true part of the second ternary will always execute.

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. 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相同。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM