进一步了解 % 模数运算符

Understanding something more about the % Modulus operator

我正在学习使用诸如 PHP 查询之类的数学运算,刚刚开始求模,我不太确定在什么情况下使用它,因为我偶然发现了一些东西,是的,我已经读过这里有一篇关于模数的帖子: Understanding The Modulus Operator %

(此解释仅适用于正数,否则取决于语言)

上面的引述是那里的最佳答案。但是如果我只关注 PHP 并且我使用这样的模数:

$x = 8;
$y = 10;
$z = $x % $y;
echo $z; // this outputs 8 and I semi know why.

Calculation: (8/10) 0 //times does 10 fit in 8.
                    0 * 10 = 0 //So this is the number that has to be taken off of the 8
                    8 - 0 = 8 //<-- answer

Calculation 2: (3.2/2.4) 1 //times does this fit
                         1 * 2.4 = 2.4 //So this is the number that has to be taken off of the 3.2
                         3.2 - 2.4 = 0.8 // but returns 1?

所以我的问题是为什么会发生这种情况。我的猜测是,在第一阶段它会得到 8/10 = 0,8 但这并没有发生。那么有人可以解释一下为什么会发生这种情况。我理解模数的基础知识,就像我做 10 % 8 = 2 一样,我半理解为什么它不 return 是这样的:8 % 10 = -2.

另外,有没有办法修改模数的工作方式?所以它会在计算中 return 一个 - 值或小数值?还是我需要为此使用其他东西

略微缩短:为什么当我在 return 中得到负数时会发生这种情况,是否有其他方法或运算符实际上可以做同样的事情并得到负数。

模数 (%) 仅适用于整数,因此您在示例底部的计算是正确的...

8/10 = 0 ( integer only ), remainder = 8-(0*10) = 8.

如果你改为 -ve 12 - -12%10...

-12/10 = -1 (again integer only), remainder = -12 - (10*-1) = -2

对于花车 - 你可以使用 fmod(http://php.net/manual/en/function.fmod.php)

<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7

(手册中的示例)