2

Possible Duplicates:
Modulus operation with negatives values - weird thing ??
Mod of negative number is melting my brain!

I tried doing 25 % -9 just for fun and the answer I got was -2 (this was on Google) and when I did this in C code I got 7. Can someone explain me why two different answers?

0

2 Answers 2

7

In C89/90, either result was allowed. The results you got from division and remainder were required to "fit" together so that (a/b)*b + a%b == a.

Starting with C99, integer division with a negative input is required to truncate toward zero. The relationship between the results from division and remainder is still required though. This means that (in effect) the result from the remainder operation always has the same sign as the left operand, so 25 % -9 must yield 7, not -2.

For what it's worth, C++ followed roughly the same path, just a few years behind C. C++98/03 has the same rules as C89/90, so for your inputs the remainder could be either negative or positive (but still needs to fit together with the result from division). Starting with C++11, it requires the same behavior as C99, so 25 % - 9 == 7.

Some other languages (e.g., Python) require that the result from remainder have the same sign as the right operand instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Upvoted since it's comprehensive and correct answer, a rarity on SO. The only thing I miss is discussion of the rationales for the different rules. Python's rule means that it's easy to e.g. compute how many taxis with passenger capacity 3 are required for a group of 10 people, while the C and C++ rule means that computations are maximally efficient on contemporary hardware. Then, there is the question why is the hardware like that. I don't know. :-)
@Cheersandhth.-Alf: Yeah, I worry a bit about trying to give rationale, especially for things in C that (as you already know) can sometimes come down to something like: "because it allowed the PDP/7 to save 3 gates in its middle-endian, fixed-point, 36-bit arithmetic", or something equally obscure.
3

If you come to think about it in a mathematical base of 9 they are the same thing as 9-2 = 7

1 Comment

@Rafid: I suspect he means the "modulo 9" equivalence class. But yes, strange wording.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.