php 如何在PHP中无余数地除数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5797625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to divide numbers without remainder in PHP?
提问by eomeroff
How does one divide numbers but exclude the remainder in PHP?
如何在 PHP 中除数但排除余数?
回答by KingCrunch
回答by Remco Beugels
PHP 7 has a new built-in function for this named intdiv
.
PHP 7 为这个名为intdiv
.
Example:
例子:
$result = intdiv(13, 2);
The value of $result
in this example will be 6
.
$result
本例中的值为6
。
You can find the full documentation for this function in the PHP documentation.
回答by ralokt
For most practical purposes, the accepted answer is correct.
对于大多数实际目的,接受的答案是正确的。
However, for builds where integers are 64 bits wide, not all possible integer values are representable as a double-precision float; See my comment on the accepted answer for details.
但是,对于整数为 64 位宽的构建,并非所有可能的整数值都可以表示为双精度浮点数;有关详细信息,请参阅我对已接受答案的评论。
A variation of
的变种
$n = ($i - $i % $m) / $m;
(code taken from KingCrunch's comment under another answer) will avoid this problem depending on the desired rounding behavior (bear in mind that the result of the modulus operator may be negative).
(代码取自另一个答案下 KingCrunch 的评论)将根据所需的舍入行为避免此问题(请记住,模数运算符的结果可能为负)。
回答by FlameStorm
In addition to decisions above like $result = intval($a / $b)
there is one particular case:
除了上述决定外,$result = intval($a / $b)
还有一种特殊情况:
If you need an integer division (without remainder) by some power of two ($b
is 2 ^ N
) you can use bitwise right shift operation:
如果你需要一个整数除法(没有余数)的一些幂($b
is 2 ^ N
),你可以使用按位右移操作:
$result = $a >> $N;
where $N is number from 1 to 32 on 32-bit operating system or 64 for 64-bit ones.
其中 $N 在 32 位操作系统上是 1 到 32 之间的数字,在 64 位操作系统上是 64。
Sometimes it's useful because it's fastest decision for case of $b is some power of two.
有时它很有用,因为对于 $b 的情况最快的决定是 2 的幂。
And there's a backward (be careful due to overflow!)operation for multiplying by power of two:
并且有一个向后(由于溢出而小心!)乘以二的幂的操作:
$result = $a << $N;
Hope this helps for someone too.
希望这对某人也有帮助。
回答by Alex
or you could just do intval(13 / 2) gives 6
或者你可以只做 intval(13 / 2) 给出 6
回答by Marco
use modulo in php:
在 php 中使用模数:
$n = $i % $m;