c modulus operator

后端 未结 5 491
独厮守ぢ
独厮守ぢ 2021-01-25 13:42

what happens when you use negative operators with %. example -3%2 or 3%-2

5条回答
  •  青春惊慌失措
    2021-01-25 14:08

    The % operator gives the remainder for integer division, so that (a / b) * b + (a % b) is always equal to a (if a / b is representable; in two's complement notation the most negative integer divided by -1 is not representable).

    This means that the behaviour of % is coupled to that of /. Prior to C99 the rounding direction for negative operands was implementation-defined, which meant that the result of % for negative operands was also implementation-defined. In C99 the rounding for / is towards zero (decimals are simply truncated), which also fixes the behaviour of % in C99.

提交回复
热议问题