gpt4 book ai didi

php - 除以零误差

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:00:58 24 4
gpt4 key购买 nike

我有这段代码抛出了错误:

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

但是还是报错。有什么想法吗?

最佳答案

您希望在除法发生之前检查 $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";
}
?>

关于php - 除以零误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19456652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com