division & modulus

a / b, a % b

當b為0時, behavior undefined,這邊討論其中一個operand為負數的情況
C89
整數除法(有負數情況下 implementation defined)
-9/7 有可能是 -1 or -2 (rounded up or rounded down)
當然此時對應的 % 就會根據除法的結果而不同 (這邊討論整數的modulus,floating point可以參考fmod)
要符合 dividend = divisor * quotient + remainder
-9 = 7 * (-1) + (-2)
-9 = 7 * (-2) + 5

C99
6.5.5 Multiplicative operators
When integers are divided, the result of the / operator is the algebraic quotient with any
fractional part discarded

總是 truncated to zero
所以 -9/7 = -1, -9%7=-2

C++
在c++03標準中 5.6 Multiplicative operators提到
If both operands are nonnegative then the remainder is nonnegative;
if not, the sign of the remainder is implementation-defined
這邊講的remainder要是正還是負為implementation defined,也就是有可能是 -2 or 5 對應的quotient是 -1, 2

This entry was posted in C Language, C++ Language. Bookmark the permalink.

Leave a Reply