Reputation: 2352
I calc -15 mod 18 and here are results:
C: -15 % 18 = -15
(http://codepad.org/DhzkZYHk)
Google: -15 mod 18 = 3
(Type -15 mod 18
into google's search box)
and results of -9 mod 5:
C: -9 % 5 = -4
Google: -9 mod 5 =1
Why these are differents? And how google calculate their mod?
Upvotes: 1
Views: 4432
Reputation: 145
Google's calculator does -15 mod 18 as
-15 = 18*(-1) + 3
giving a remainder of 3, whereas C evaluates it as
-15 = 18*(0) - 15
and hence the expression becomes -15.
In general,
a = (a/b)*b + a%b
holds.
Upvotes: 2
Reputation: 145899
Because the %
operator in Google is a modulus operator and the %
operator in C is a remainder operator.
Modulus and remainder operators differ with respect to negative values. With the modulus operator the sign of the result is the sign of the divisor and with the remainder operator the sign of the result is the sign of the dividend.
Upvotes: 2