简体   繁体   中英

Warning: Division by zero in loop

I have this code:

for ($y = 0; $y < $numRows; $y++) {
    for ($i = 0; $i < $numRows; $i++) {
        ${'contaH' . $i}[]=${'arrHoriz' . $i}[$y]/$arr[$y];
    }
}

echo $contaH0[0]."\n";

that output is:

Warning: Division by zero in C:\Users\xx\VertrigoServ\www\AHP\new\demo.php on line 66
Warning: Division by zero in C:\Users\xx\VertrigoServ\www\AHP\new\demo.php on line 66
Warning: Division by zero in C:\Users\xx\VertrigoServ\www\AHP\new\demo.php on line 66
Warning: Division by zero in C:\Users\xx\VertrigoServ\www\AHP\new\demo.php on line 66
0.300618921309 

but if i change this line:

${'contaH' . $i}[]=${'arrHoriz' . $i}[$y]/$arr[$y];

to

${'contaH' . $i}[]=${'arrHoriz' . $i}[$y]/$arr[0];

the output is:

0.300618921309 

What is the reason of the warning in first code ?

$arr没有像您想象的那样有太多元素,或者有很多0或空元素。

The reason is that in your loop, $arr[$y] isn't always equal to 0. Somewhere in your array it's zero (or not defined). You should do a check to see if your denominator is zero before doing any division and properly handle the case where it's zero.

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