Understanding something more about the % Modulus opperator

匿名 (未验证) 提交于 2019-12-03 00:44:02

问题:

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)

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? 

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.

回答1:

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

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

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

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

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 

(Example from manual)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!