我是PHP新手,我的网站上有一个错误,无法找到正确的解决方法。
错误:
Warning: Division by zero
我正在使用的代码:
public function percent($num_amount, $num_total)
{
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count = round($count2);
return $count;
}
我知道这与除以 0 有关,这显然不能。但是我如何更改它并修复此错误?
简单地....
public function percent($num_amount, $num_total)
{
if($num_total > 0){
$count1 = $num_amount / $num_total;
$count2 = $count1 * 100;
$count = round($count2);
return $count;
}else{
return 0; // or whatever you want
}
}
如果$num_total
为零,则检查$num_amount
是否也为零。如果是,则返回一个合适的值(可能是 100%)。如果$num_amount
不是零,那么您有一些逻辑错误,您应该标记。