【问题标题】:How to proportionally decrease positive and negative numbers如何按比例减少正数和负数
【发布时间】:2018-08-21 08:35:40
【问题描述】:

我有两个变量:

$points - could be positive or negative $time_elapsed -is always positive

我正在尝试根据$time_elapsed 按比例减少$points。我不能使用减法,因为它不像我需要的那样“成比例”。我需要类似于除法的东西,但这总是会减少 $points(除法会增加数字,如果它是负数),以便我得到以下结果:

$points = -12;
$time_elapsed = 4;
$points/time_elapsed = -48;

$points = 12;
$time_elapsed = 4;
$points/time_elapsed = 3;

我不能使用 abs(),因为它会在点数为 -12 时返回 -3,而我真的需要它返回 -48(我总是需要 $time_elapsed 倍小于 $points 的东西)。 我不能使用 if 条件或类似的东西。这甚至可能吗?

【问题讨论】:

  • $time_elapsed 在哪里?它和$point有什么关系?
  • 为清晰起见进行了编辑。
  • 如果您有三个变量的值表,您可以使用数值方法来获得它们之间的近似关系(方程式)。
  • 为什么不使用条件运算符?
  • 可能是学校作业。

标签: php algorithm algebra


【解决方案1】:

您可以提取符号位并使用它来避免条件运算符(虽然这个限制是奇怪的想法):

 $sgn = ($points >> 31) & 1  //(for 32-bit variables)
 return   $points * $sgn * $time + $points * (1 - $sgn) / $time

 //returns $points * $time for negative and $points / $time for positive

【讨论】:

  • 和使用abs()是一样的。对于 $points = -12 和 $time = 4,它返回 -3 而不是 -48,从而增加 $points 而不是减少它。
【解决方案2】:

这会奏效。没有条件!

Fiddle here

function getPoints($points, $time_elapsed)
{
    $is_positive = $points > 0;

    $converters = [
        true => function($points, $time_elapsed) {
            return $points / $time_elapsed;
        },
        false => function($points, $time_elapsed) {
            return $points * $time_elapsed;
        }
    ];

    return $converters[$is_positive]($points, $time_elapsed);
}

echo getPoints(-12, 4), PHP_EOL;
echo getPoints(12, 4), PHP_EOL;

【讨论】:

  • 这个$points > 0其实是一个if条件,即使没有直接涉及到if。
  • @MichaelZukowski 从技术上讲,这是一个表达式;如果他们可以使用/,他们可以使用>
猜你喜欢
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
相关资源
最近更新 更多