百科狗-知识改变命运!

intdiv() - 对除法结果取整 - php 数学函数

梵高2年前 (2023-11-21)阅读数 20#技术干货
文章标签异常

intdiv()

版本:php7

(PHP 7)

intdiv() - 对除法结果取整 - php 数学函数

对除法结果取整

说明

intdiv(int $dividend,int $divisor): int

返回$dividend除以$divisor商数的整数部分。

参数

$dividend

被除数。

$divisor

除数。

返回值

$dividend除以$divisor的商,对该商取整。

错误/异常

如果$divisor是0,将抛出DivisionByZeroError异常。如果$dividend是PHP_INT_MIN并且$divisor是-1,将抛出ArithmeticError异常.

范例

Example #1intdiv()的一些例子


int(1)
int(-1)
int(-1)
int(1)
int(1)
int(1)
Fatal error: Uncaught ArithmeticError: Division of PHP_INT_MIN by -1 is not an integer in %s on line 8
Fatal error: Uncaught DivisionByZeroError: Division by zero in %s on line 9
This does indeed seem to be equal to intdiv:

However, this isn't:

Consider an example where either of the parameters is negative:

@AmeenRoss 
This does NOT seem to be equal to intdiv:

See this example code

//Output
5
4
For earler versions PHP you may use:
function intdiv_1($a, $b) {
  $a = (int) $a;
  $b = (int) $b;
  return ($a - fmod($a, $b)) / $b;
}
Without intdiv(), the following may be a good way (with $a and $b of type integer and not too big) :

because in case of divisible integers, the result will be integer and there is no risk of float appearing round but below their represented value (like the case (0.1+0.7)*10).
$a and $b really needs to be of type integer though. 
If they are too big and indivisible, some precision will be lost during the conversion to float and the result may be inaccurate.
$a = 57;
$b = 3;
var_dump(
  intdiv($a,$b),
  intdiv_1($a,$b),
  intdiv_2($a,$b)
);
function intdiv_1($a, $b){
  return ($a-$a%$b)/$b;
}
function intdiv_2($a, $b){
  return floor($a/$b);
}
//intdiv($a, $b) == floor($a/$b) == ($a-$a%$b)/$b

Aren't this?!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)