奇怪的模数运算符结果 - PHP

Strange Modulus Operator Result - PHP

我正在开发一个 PHP 应用程序,数学运算导致错误答案,显示错误结果。所以,我开始深入挖掘,经过几个小时的努力,我发现了这个问题。

这里是有问题的表达式:

echo -1 % 26;

答案应该是 25 但它给出了 -1。不知道,是不是我的表情有问题?

PHP 输出:

计算器:

哪位大侠能指点一下,问题出在哪里?

这是预期的行为。 From the PHP manual

The result of the modulo operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a

如果被除数的符号(%左边的部分)改变,结果也会改变。您可以通过添加除数来找到负余数的正等价物。 -1 等于 25 模 26,因为 -1 + 26 = 25。

因此您可以执行以下操作以获得肯定的结果:

function modulo($dividend, $divisor) {
  $result = $dividend % $divisor;
  return $result < 0 ? $result + $divisor : $result;
}

$calculation = modulo(-1, 26); // 25
$calculation2 = modulo(51, 26); // 25

怎么样?

$ cat test.php
<?php

function truemod($num, $mod) {
  return ($mod + ($num % $mod)) % $mod;
}

echo truemod(-1, 26).PHP_EOL;
?>

输出

$ php test.php 
25