How is -13 d = -13 in PHP?

后端 未结 4 903
南笙
南笙 2020-12-06 17:45

Derived from this question : (Java) How does java do modulus calculations with negative numbers?

Anywhere to force PHP to return positive 51?

update

4条回答
  •  自闭症患者
    2020-12-06 17:56

    The modulo operation should find the remainder of division of a number by another. But strictly speaking in most mainstream programming languages the modulo operation malfunctions if dividend or/and divisor are negative. This includes PHP, Perl, Python, Java, C, C++, etc.

    Why I say malfunction? Because according to mathematic definition, a remainder must be zero or positive.

    The simple solution is to handle the case yourself:

    if r < 0  then r = r + |divisor|;
    

    |divisor| is the absolute value of divisor.

    Another solution is to use a library (as @Gordon pointed). However I wouldn't use a library to handle a simple case like this.

提交回复
热议问题