除零错误

时间:2013-10-18 18:29:18

标签: php division divide-by-zero

我有这个代码抛出错误:

<?php

    $val1 = $totalsum;
    $res = ( $val1 / $val2) * 100;
    $val2 = count($allcontent);
    $res = ( $val1 / $val2) * 100;
    // 1 digit after the decimal point
    $res = round($res, 1); // 66.7

    echo "Success: ";
    echo $res;
    echo "%";

?>

我尝试添加此行:

if ($res === 0) 
{ 
   echo "not eligible"; 
}

但仍然会出错。任何想法?

5 个答案:

答案 0 :(得分:10)

你想在分割发生之前检查$ val2:

<?php
$val1 = $totalsum;
$val2 = count($allcontent);
if($val2 != 0)
{
    $res = ( $val1 / $val2) * 100;
    // 1 digit after the decimal point
    $res = round($res, 1); // 66.7
    echo "Success: ".$res."%";
}
else
{
    echo "Count of allcount was 0";
}
?>

答案 1 :(得分:2)

您的代码中包含以下内容:

$val2 = count($allcontent);

如果$allcontent数组为空,那么$val2的值将为0,您将基本上这样做:

$res = ( $val1 / 0) * 100;

正如预期的那样,这将导致PHP返回'除以零'错误。

要确保不会发生这种情况,只需使用if声明:

if ($val2 != 0) {
    $res = ( $val1 / $val2) * 100;
    // 1 digit after the decimal point
    $res = round($res, 1); // 66.7
    echo "Success: ";
    echo $res;
    echo "%";
}

可以使用sprintf()重写:

if ($val2 > 0) {
    $res = round( ($val1 / $val2) * 100 , 1); // 66.7
    echo sprintf('Success: %d%%', $res); // % is used for escaping the %
}

它做同样的事情,但在我看来看起来更清洁。

答案 2 :(得分:1)

if($val2!=0){
  //Do it
}else{
  //Don't
}

答案 3 :(得分:0)

在尝试将$ val1与它分开之前,确保$ val2不为零。试试这个:

<?php
    $val1 = $totalsum;
    $res = ( $val1 / $val2) * 100;
    $val2 = count($allcontent);

    if( $val2 != 0 ){
        $res = ( $val1 / $val2) * 100;
        // 1 digit after the decimal point
        $res = round($res, 1); // 66.7
        echo "Success: ";
        echo $res;
        echo "%";
    }
?>

答案 4 :(得分:-2)

我猜测$val2即将出现在0.确保$allcontent正在初始化并填充。