Home  >  Article  >  Backend Development  >  PHP remainder (modulo) operation

PHP remainder (modulo) operation

不言
不言Original
2018-04-24 16:32:3923322browse

This article mainly introduces the remainder (modulus) operation in PHP, which has a certain reference value. Now I share it with everyone. Friends in need can refer to it

Recommended Manual: php complete self-study manual

Let’s look at the next small case first:

    $n = 8.45;
    $result = $n*100;
    echo gettype($result);
    var_dump($result);
    echo intval($n*100).&#39;<br>&#39;;
    echo $result%100;

Output:

double
float 845
844
44

Are you a little surprised to see this result?

In fact, the essence is intval((double) 845) = 944; because we used asking for remainder (modulo) operator %, while the operands of the modulo operator will be converted to integers (except for the decimal part) before operation.

Recommended related articles: ​​
1.php Method of taking remainder from floating point number
2.What are the common operators in php
Related video recommendations:
1.Dugu Jiujian (4)_PHP video tutorial

In addition, the result of the modulo operator % is the same as the sign (sign) of the dividend. That is, $a (dividend) % $b (divisor) has the same sign as the result. Let’s look at a few examples:

Such as:

    echo (5 % 3)."\n";           
    echo (5 % -3)."\n";       
    echo (-5 % 3)."\n";          
    echo (-5 % -3)."\n";

Output:

2 2 -2 -2

Let's introduce another Math function related to remainder fmod(). This function mainly returns the floating point remainder of division.

float fmod ( float $x , float $y )

返回被除数(x)除以除数(y)所得的浮点数余数。余数()的定义是:x = i * y + r,其中 是整数。如果 y 是非零值,则 x 的符号相同并且其数量值小于 y。 其实实质就是x/y的浮点数余数。

例子:

$x = 5;
$y = 2;
// $t = mod($x, $y);//Fatal error: Call to undefined function mod()
echo &#39;我是fmod($x, $y)输出的值:&#39;.fmod($x, $y);
echo "<br>";
echo &#39;我是$x % $y输出的值:&#39;.$x % $y;

结果:

我是fmod($x, $y)输出的值:1

我是$x % $y输出的值:1

    $x = 5.8;
    $y = 2.5;
    // $t = mod($x, $y);//Fatal error: Call to undefined function mod()
    echo &#39;我是fmod($x, $y)输出的值:&#39;.fmod($x, $y);
    echo "<br>";
    echo &#39;我是$x % $y输出的值:&#39;.$x % $y;

结果:

我是fmod($x, $y)输出的值:0.8

我是$x % $y输出的值:1

注意的是,PHP里并没有mod()函数,使用时应注意。

小结:

1、%求余的时候,就是先把运算之前的被除数和除数都转换成整数(除去小数部分)

2、fmod()就类似于数学里面的求余运算。

相关推荐:

详解使用PHP求两个字符串最长公共子串

The above is the detailed content of PHP remainder (modulo) operation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn