如何按比例减少正数和负数

时间:2018-03-13 07:11:12

标签: php algorithm algebra

我有两个变量:

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

我正在尝试根据$points按比例减少$time_elapsed。我不能使用减法,因为它不是我需要它的“比例”。我需要类似于除法的东西,但是总是减少$ 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的东西)。 我不能使用条件或类似的东西。这甚至可能吗?

2 个答案:

答案 0 :(得分:0)

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

 $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

答案 1 :(得分:0)

这会奏效。没有条件!

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;