开发者

Modulus with a negative number

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开发者_Python百科 did this in C code I got 7. Can someone explain me why two different answers?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜