PHP:避免被零除的优雅方法 [英] PHP: Elegant way to avoid division by zero
问题描述
很像这个站点,我当前的项目具有声誉,在我正在处理的脚本中,我需要计算两个用户的声誉之间的比率.
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.
$attacker->ratio = $defender->rep / $attacker->rep;
$defender->ratio = $attacker->rep / $defender->rep;
这样做,我有时可能会导致除数的声誉为0,这很糟糕!
In doing so I may occasionally end up with the divisor's reputation being 0, which sucks!
很明显,我可以添加一些检查,但是我想知道是否还没有发明更漂亮的解决方案,例如@
infront,但是我知道这不是一个好主意.
Obviously I can add a couple of checks, but I was wondering if a prettier solution hasn't been invented, something like @
infront, but I know that's not a good idea..
推荐答案
假设正数有效,则确保最小除数为1.
Assuming positive numbers are valid then ensure the lowest divisor value will be 1.
$defender->ratio = $attacker->rep / max($defender->rep, 1);
//--------------------------------------------
// --------------------------------------------
别人建议的代码,
@php_nub_qq建议使用备用代码...
在今天的php
@php_nub_qq suggested alternate code...
In today's php
$defender->ratio = $attacker->rep / ($defender->rep ?? 1);
las,@ php_nub_qq提供的此代码在PHP 7.4中不起作用;-((请参阅注释中的@OceanBt ...感谢他们的纠正!:)
Alas, this code provided by @php_nub_qq does not work in PHP 7.4 ;-( see @OceanBt in the comments... I thank them for the correction! :)
所以,在这里,我正在维护我从未感兴趣的代码.现在,该代码显示为特定于PHP版本的!这是更正...
so, Here I am maintaining code that I never was interested in. And now, is shown to be PHP version specific! Here is the correction...
$ y = 100/($ x?:1);
$y = 100/($x ?: 1);
我为什么要这样做? 1)注意我的代码仍然可以正常工作!避免将聪明的功能"用于生产代码. 2)因为有人认为答案更好"并不意味着他们这样做!
Why am I doing this? 1) Notice my code still works fine! Avoid 'clever features' for production code. 2) Because someone believes that have a 'better answer' doesn't mean they do!
我不介意对其他人的代码进行这种维护!这是真实的世界!我们必须这样做.我发布它的原因是:
我确实在尝试帮助程序员学习.
I don't mind doing this maintainance of the code of someone else! This is the real world! We have to do this. I posted it because:
I really am trying to help programmers to learn.
//我对改进"我发布的内容的想法...
// My thoughts about the 'improvement' to what I posted...
imo,您的建议与我的方法不同!我专门使用了"max",因为它强制限制数字范围.您可以嵌套最小"和最大"功能,以强制限制范围.
imo, that suggestion of yours isn't the same as my approach! I specifically used 'max' as it forces a limit on a range of numbers. You can nest the 'min' and 'max' functions also to force a limited range.
您的方法是选择",而不是为什么我回答了我. :)
Your method is a 'selection' and not why I did the answer I did. :)
这篇关于PHP:避免被零除的优雅方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!