I’m using PHP for a project and I expect -1 % 4 to return 3. However, the final result is -1 in PHP and I don’t know why:
php > echo -1 % 4;
-1
I checked in Ruby IRB and the result is 3:
irb(main):001:0> puts -1 % 4
3
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because it’s defined in terms of division, such that:
For divisions with negative results, there are two possible definitions; either you round toward zero, or you round toward negative infinity. Different programming languages have made that choice differently.
See http://en.wikipedia.org/wiki/Modulo_operator#Remainder_calculation_for_the_modulo_operation for more information.