dongshi1869 2016-06-09 13:13
浏览 111
已采纳

看看数字a是否比b更接近于c

I am currently trying to make a function that can tell if number a is closer to c than the number b is to c.

I have tried to do comparisons like so: (taking a and b from c and comparing those)

$c = 10;
$b = 2;
$a = 3;

$b_check = $c - $b; // = 8.
$a_check = $c - $a; // = 7.

In my head, I thought that whatever number (a or b) is smaller means that it's gonna be the closer number to c, though that worked using positive integers, but when it came to negative integers it gave the complete wrong outcome.

I was wondering if maybe there was an in-built function in PHP for this or if there's a better mathematical method for achieving this?

  • 写回答

2条回答 默认 最新

  • dongqin8652 2016-06-09 13:20
    关注

    If (a - c) * (a - c) < (b - c) * (b - c) would do it. This gets round the negative number issue and is the way us old cats do it in C.

    Else you could use Math.abs(a - c) < Math.abs(b - c) but the other way can be quicker for some types, but you need to take care not to overflow your type and there's a potential for a ruinous wraparound effect for some types too.

    Profile it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?