【问题标题】:Comparing values but taking into account negative values比较值但考虑负值
【发布时间】:2018-09-25 12:49:51
【问题描述】:

我有一个$total 和一个$balance。余额永远不会大于总数,但两者都可能是负数。本质上,我正在尝试查看余额是否在零和总数之间。

所以,

if (($total < 0 && $balance < $total) || ($total > 0 && $balance > $total)) { /** BAD **/ }

if (between($total < 0 ? $total : 0, $total < 0 ? 0 : $total, $balance) { /** BAD **/ }

当然有两种方法可以实现这一点,但是有没有办法减少这里的逻辑量?我确信我应该知道的数论“聪明”的东西......但不知道。

我使用的是 PHP,但比较的原则应该从任何语言/算法翻译过来。

来自 cmets 的反馈

如果总计为负数,则余额必须为负数且不小于总计。 如果总计为正,则余额必须为正且不大于总计

也许一张图片会有所帮助!

Balance : BAD | Allowable -ve balances | Allowable +ve balances | BAD Total : -5 .. -4 .. -3 .. -2 .. -1 .. 0 .. 1 .. 2 .. 3 .. 4 .. 5

进一步的反馈

在“余额永远不会大于总数,但两者都可能是负数”的问题中......我说的是数量,而不是价值。我想我没有说清楚:https://study.com/academy/lesson/what-is-magnitude-definition-lesson-quiz.html

解决方案

基于提供的 cmets。

<?php

class RangeTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @param int $balance
     * @param int $total
     * @param bool $expected
     *
     * @dataProvider provideRangeValues
     */
    public function testRange(int $balance, int $total, bool $expected)
    {
        $this->assertEquals((($total / abs($total)) * ($total - $balance) >= 0), $expected);
    }

    public function provideRangeValues()
    {
        return
            [
                'Positive Balance = Positive Total' => [10, 10, true],
                'Positive Balance < Positive Total' => [5, 10, true],
                'Positive Balance > Positive Total' => [10, 5, false],
                'Negative Balance = Negative Total' => [-10, -10, true],
                'Negative Balance < Negative Total' => [-5, -10, true],
                'Negative Balance > Negative Total' => [-10, -5, false],
            ];
    }
}

【问题讨论】:

  • 感谢您的来信。现在我明白了,我误解了你的问题 - 我认为它更多地是关于财务或会计的。

标签: php algorithm numbers


【解决方案1】:

您可以尝试以下方法:

if (  min(1, max(-1, $total)) * ($total - $balance) >= 0 ) {

   // all good 

基于OP's comments,因为总数永远不会为零。我们还可以这样做:

if ( ($total/abs($total)) * ($total - $balance) >= 0 ) {

   // all good 

【讨论】:

  • @meowgoesthedog 没错!问题陈述让我想到了复杂的解决方案:-}
  • @meowgoesthedog 再次阅读问题陈述后,我现在真的很困惑。你的答案是对的
  • 我已对问题添加了一些反馈。
  • @RichardAQuadling 现在检查我编辑的答案。它应该适用于您的情况。如果可以保证 $total 永远不会为零,则可以进一步优化。
  • 几乎正确。检查我发布的解决方案(基于您的代码)。余额可以等于总计,所以差额计算可以为零,所以&gt;= 0 而不是&gt; 0。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 2014-06-30
  • 1970-01-01
相关资源
最近更新 更多