c modulus operator

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

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

相关标签:
5条回答
  • 2021-01-25 13:48

    In C99 a % b has the sign of a, pretty much like fmod in math.h. This is often what you want :

    unsigned mod10(int a)
    {
        int b = a % 10;
        return b < 0 ? b + 10 : b;
    }
    
    0 讨论(0)
  • 2021-01-25 13:56

    According to Kernighan & Ritchie, 2nd edition, page 39, 2.5:

    ...the sign of the result for % are machine-dependent for negative operands, as is the action taken on overflow or underflow.

    0 讨论(0)
  • 2021-01-25 14:01

    In C89, C90, and C++03 the standards requires only that (a/b)*b+a%b == a for the / and % operators.

    If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined

    Edit: In C99 a negative number will be returned if the first argument is negative

    0 讨论(0)
  • 2021-01-25 14:06

    In C99

    -3%2=-1
     3%-2=1
    

    In C90 -3%2 or 3%-2 --> Implementation defined

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题