PHP: Elegant way to avoid division by zero

后端 未结 7 601
小鲜肉
小鲜肉 2020-12-30 07:19

Much like this site, my current project has reputation and in the script that I\'m working on I need to calculate the ratio between two users\' reputations.

         


        
7条回答
  •  暖寄归人
    2020-12-30 07:45

    I don’t recommend to change any user’s reputation artificially solely to make the math work. Instead you can do this:

    function calc_rep_ratio($self, other)
    {
        if ($self->rep != 0) {
            return $other->rep / $self->rep;
        } else {
            return NAN;
        }
    }
    

    Then use the function

    $defender->ratio = calc_rep_ratio($defender, $attacker);
    $attacker->ratio = calc_rep_ratio($attacker, $defender);
    

    In the presentation, you can check for the number

    if (is_nan($user->ratio)) {
        echo 'No ratio available';
    } else {
        echo $user->ratio;
    }
    

提交回复
热议问题