Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...