我正在学习如何处理一些数学问题,比如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,并且我半理解为什么它不返回这样的东西:8 % 10 = -2。
另外,是否有一种方法来修改模块的工作方式?所以它会在计算中返回一个-值还是一个十进制值?或者我还需要用别的东西来做这个
小缩短:为什么这会发生,当我得到一个负数作为回报,是否有其他的方式或运算符,实际上可以做同样的,并得到负数。
发布于 2018-02-07 11:15:58
模数(%)只适用于整数,因此您在示例底部的计算是正确的。
8/10 =0(仅为整数),余数= 8-(0*10) = 8。
如果你有-ve 12 --12%10.
-12/10 = -1 (同样仅为整数),余数= -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(例如来自手册)
https://stackoverflow.com/questions/48662225
复制相似问题