php 除以零误差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19456652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Division by zero error
提问by Seth-77
I have this code throwing up the error:
我有这个代码抛出错误:
<?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 "%";
?>
I have tried adding this line:
我试过添加这一行:
if ($res === 0)
{
echo "not eligible";
}
but it still gives the error. any ideas?
但它仍然给出错误。有任何想法吗?
回答by Chris Rasco
You'd want to check $val2 before the division occurs:
您想在除法之前检查 $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";
}
?>
回答by Amal Murali
You have the following in your code:
您的代码中有以下内容:
$val2 = count($allcontent);
If the $allcontent
array is empty, then the value of $val2
will be 0
, and you will essentially be doing:
如果$allcontent
数组为空,则 的值$val2
将为0
,并且您实际上将执行以下操作:
$res = ( $val1 / 0) * 100;
As expected, this will cause PHP to return the 'Division by zero' error.
正如预期的那样,这将导致 PHP 返回“被零除”错误。
To make sure this doesn't happen, simply use an if
statement:
为确保不会发生这种情况,只需使用以下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 "%";
}
This can be rewritten using sprintf()
:
这可以使用sprintf()
以下方法重写:
if ($val2 > 0) {
$res = round( ($val1 / $val2) * 100 , 1); // 66.7
echo sprintf('Success: %d%%', $res); // % is used for escaping the %
}
It does the same thing, but looks a bit more cleaner, in my opinion.
在我看来,它做同样的事情,但看起来更干净一些。
回答by undone
if($val2!=0){
//Do it
}else{
//Don't
}
回答by Zest
Make sure $val2 is NOT zero before trying to divide $val1 with it. Try this:
在尝试将 $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 "%";
}
?>
回答by Hyman B
I'm guessing $val2
is coming out to 0. Make sure $allcontent
is being initialized and filled.
我猜$val2
是 0。确保$allcontent
正在初始化和填充。