我有一个$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,但是比较原则应该从任何语言/算法中转换出来。
来自评论的反馈
如果总数为负数,则余额必须为负数,且不得少于总数。如果总数为正,则平衡必须为正且不大于总余额。
也许一张照片会有帮助!
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
溶液
根据所提供的评论。
<?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],
];
}
}
发布于 2018-09-25 04:52:57
您可以尝试以下方法:
if ( min(1, max(-1, $total)) * ($total - $balance) >= 0 ) {
// all good
基于OP's comments,因为总不可能是零。我们还可以做以下工作:
if ( ($total/abs($total)) * ($total - $balance) >= 0 ) {
// all good
https://stackoverflow.com/questions/52498643
复制相似问题