除以零错误

6

我有这段代码,它出现了错误:

<?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"; 
}

但是它仍然会出现错误。有什么想法吗?

你能把你的代码缩进一下吗? - Jason OOO
抱歉,这是脚本中的写法! - Seth-77
5个回答

16

在进行除法之前,您需要检查 $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";
}
?>

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 %
}

我个人认为,它执行的功能相同,但看起来更加清晰。


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

0

在尝试用$val2除以$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 "%";
    }
?>

欢迎来到Stack Overflow!虽然这段代码可能有助于解决问题,但它并没有解释为什么以及如何回答这个问题。提供这种额外的上下文将显著提高其长期教育价值。请编辑您的答案以添加说明,包括适用的限制和假设。 - Toby Speight

-2
我猜测$val2的值为0。请确保$allcontent被初始化并填充了内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接