Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c - 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 did this in C code I got 7. Can someone explain me why two different answers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...