了解有关%Modulus运算符的更多信息 [英] Understanding something more about the % Modulus operator

查看:115
本文介绍了了解有关%Modulus运算符的更多信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用PHP查询之类的数学工具,只是进行了模数运算,由于我偶然发现某些东西,我不确定在什么情况下使用它,是的,我已经读过其中一篇关于模数: 了解模量运算符%

I am learning to work with some math like PHP query and just got to the modulo, I am not quite sure in what situations to use this because of something i stumbled on and yes I did already read one of the posts here about the modulo : Understanding The Modulus Operator %

(此说明仅适用于正数,因为否则将取决于语言)

(This explanation is only for positive numbers since it depends on the language otherwise)

上面的引文是最重要的答案.但是,如果我只关注PHP,并且使用如下模数:

The quote above is in the top answer there. But if I focus on PHP only and i use the modulo like this:

$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.

So my question is why does this exactly happen. my guess would be that in the first phase it would get 8/10 = 0,8 but this doesn't happen. So can someone explain a bit about why this happens. I understand the modulo's basics like if I do 10 % 8 = 2 and I semi understand why it doesn't return something like this: 8 % 10 = -2.

还可以修改模数的工作方式吗?因此它将在计算中返回-值或十进制值?还是我需要为此使用其他东西

Also, is there a way to modify how the modulo works? so it would return a - value or a decimal value in the calculation? or would I need to use something else for this

略微简化:为什么当我得到一个负数作为回报,并且还有其他方法或运算符可以实际做同样的事情并得到负数时,为什么会发生这种情况呢?

Little shortened: why does this happen when I get a negative number in return and is there some other way or operator that can actually do the same and get in the negative numbers.

推荐答案

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

Modulus (%) only works for integers, so your calculation at the bottom of your example is correct...

8/10 = 0(仅整数),余数= 8-(0 * 10)= 8.

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

如果您使用的是-ve 12--12%10 ...

If you instead had -ve 12 - -12%10...

-12/10 = -1(再次为整数),余数= -12-(10 * -1)= -2

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

对于浮点数-您可以使用fmod( http://php.net/manual /en/function.fmod.php )

For floats - you can use 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

(手册中的示例)

这篇关于了解有关%Modulus运算符的更多信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆