PHP 整數除法



PHP 引入了一個新的函式 intdiv(),它執行其運算元的整數除法並返回整數結果。

intdiv() 函式返回兩個整數引數的整數商。如果 "a/b" 的結果是商 "c" 和餘數 "r",則:

a=b*c+r

在這種情況下,intdiv(a,b) 返回 c

intdiv ( int $x , int $y ) : int

$x 和 $y 是除法表示式中的分子和分母部分。intdiv() 函式返回一個整數。如果兩個引數都是正數或都是負數,則返回值為正數。

示例 1

如果分子 < 分母,intdiv() 函式返回 "0",如下所示:

<?php
   $x=10;
   $y=3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
   $r=intdiv($y, $x);
   echo "intdiv(" . $y . "," . $x . ") = " . $r;
?>

它將產生以下輸出

intdiv(10,3) = 3
intdiv(3,10) = 0

示例 2

在下面的示例中,intdiv() 函式返回負整數,因為分子或分母為負數。

<?php
   $x=10;
   $y=-3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
   $x=-10;
   $y=3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
?>

它將產生以下輸出

intdiv(10,-3) = -3
intdiv(-10,3) = -3

示例 3

如果分子和分母都是正數或都是負數,intdiv() 函式返回正整數。

<?php
   $x=10;
   $y=3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";

   $x=-10;
   $y=-3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r ;
?>

它將產生以下輸出

intdiv(10,3) = 3
intdiv(-10,-3) = 3

示例 4

在下面的示例中,分母為 "0"。這將導致DivisionByZeroError 異常。

<?php
   $x=10;
   $y=0; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
?>

它將產生以下輸出

PHP Fatal error:  Uncaught DivisionByZeroError: Division by zero in hello.php:4
廣告