Jump to content

Division by zero


Dusaro

Recommended Posts

Well, I am currently working on a Kill/Death Table when the players insert there kills and deaths along with a screenshot of proof.

I have got most of it down except for a Warning: Division by zero in /home/a2186214/public_html/table/index.php on line 43 error.

 

This is the code I am using to calculate the kill/deaths:

if ($row['kills'] >= 1)
{
$kdr = $row['kill']/$row['death'];
}
elseif ($row['death'] >= 1)
{
$kdr = $row['kill']/$row['death'];
}
else
$kdr = '0';

How would I fix this?

Link to comment
https://forums.phpfreaks.com/topic/252628-division-by-zero/
Share on other sites

if i was to use both of your answers, i get this:

This now gives the Kill/Death at 0

if ($row['kills'] != 0 && $row['death'] != 0){	
$kdr = $row['kill']/$row['death'];
} else {
$kdr = '0';
}

 

If I try this:

It still shows as Kill/Death at 0.

if ($row['kills'] >= 1 && $row['death'] >= 1){	
$kdr = $row['kill']/$row['death'];
} else {
$kdr = '0';
}

 

So these are fixing the division by 0 error but it is not calculating the kill/death.

Link to comment
https://forums.phpfreaks.com/topic/252628-division-by-zero/#findComment-1295121
Share on other sites

For a kill/death ratio (KDR) the 'death' is the divisor and is the only value that cannot be zero. However, if the 'kill' value is zero, then the KDR will be zero - which can be used in the calculation. So, there is no need to add special handling for the kill value.

 

The problem you have is if the 'death' value is zero. In that instance there really is no KDR that can be calculated. As you get smaller and smaller values for death as they approach zero, the KDR will approach infinity.

 

I have seen games that simply report no KRD when the user had no deaths or report a KDR based upon one death. I think the latter 'looks' better. But, this is a judgement call because when there are no deaths there is no real KDR value.

 

So, to use a default of 1 death when the deaths are zero becomes a very trivial solution.

if ($row['death'] == 0) { $row['death'] = 1; }
$kdr = $row['kill'] / $row['death'];

 

The only other - legitimate - options are to show no KDR (e.g. '--') or use something such as an infinity symbol (e.g. '∞'. That would look pretty 1337. But, you'd probably only want to use that if they had at least one kill.

if ($row['death'] == 0)
{
    if ($row['kill'] == 0) { $kdr = 0; }
    else { $kdr = '∞'; }
}
else
{
    $kdr = $row['kill'] / $row['death'];
}

Link to comment
https://forums.phpfreaks.com/topic/252628-division-by-zero/#findComment-1295124
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.