了解有关%Modulus运算符的更多信息

问题描述 投票:0回答:1

我正在学习像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

另外,有没有办法修改模数的工作原理?所以它会在计算中返回-值或小数值?或者我需要为此使用别的东西

稍微缩短:为什么当我得到一个负数作为回报时会发生这种情况,并且还有一些其他方式或运算符可以实际上做同样的并且得到负数。

php math syntax modulo modulus
1个回答
2
投票

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

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

(手册示例)

© www.soinside.com 2019 - 2024. All rights reserved.