php - 比较值但考虑负值
问题描述
我有一个$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],
];
}
}
解决方案
您可以尝试以下方法:
if ( min(1, max(-1, $total)) * ($total - $balance) >= 0 ) {
// all good
根据OP 的评论,因为总不能为零。我们还可以执行以下操作:
if ( ($total/abs($total)) * ($total - $balance) >= 0 ) {
// all good
推荐阅读
- c# - 如何填写俄罗斯方块字段
- html - 在表格行中并排获取按钮的问题
- python - 列表相对于字典的不同组合
- python - 如何将单词列转换为标题列,将两篇文章的名称转换为行的标题?
- google-cloud-platform - 为 terraform 设置 gcs 后端的问题
- node.js - 使用 fetch API 处理 XML 请求
- javascript - 使用 JS 时字体真棒图标和面板无法正确显示
- docker - 使用 2 个不同版本和端口号运行弹性搜索 docker 时出现问题
- authentication - 在 django rest 框架中使用“令牌”作为身份验证方案的动机是什么?
- javascript - 使用 Javascript 的表搜索功能