Modulo operation with negative numbers

前端 未结 12 1426
旧巷少年郎
旧巷少年郎 2020-11-22 06:10

In a C program i was trying the below operations(Just to check the behavior )

 x = 5 % (-3);
 y = (-5) % (3);
 z = (-5) % (-3); 

printf(\"%d ,%d ,%d\", x, y         


        
12条回答
  •  名媛妹妹
    2020-11-22 06:46

    According to C99 standard, section 6.5.5 Multiplicative operators, the following is required:

    (a / b) * b + a % b = a
    

    Conclusion

    The sign of the result of a remainder operation, according to C99, is the same as the dividend's one.

    Let's see some examples (dividend / divisor):

    When only dividend is negative

    (-3 / 2) * 2  +  -3 % 2 = -3
    
    (-3 / 2) * 2 = -2
    
    (-3 % 2) must be -1
    

    When only divisor is negative

    (3 / -2) * -2  +  3 % -2 = 3
    
    (3 / -2) * -2 = 2
    
    (3 % -2) must be 1
    

    When both divisor and dividend are negative

    (-3 / -2) * -2  +  -3 % -2 = -3
    
    (-3 / -2) * -2 = -2
    
    (-3 % -2) must be -1
    

    6.5.5 Multiplicative operators

    Syntax

    1. multiplicative-expression:
      • cast-expression
      • multiplicative-expression * cast-expression
      • multiplicative-expression / cast-expression
      • multiplicative-expression % cast-expression

    Constraints

    1. Each of the operands shall have arithmetic type. The operands of the % operator shall have integer type.

    Semantics

    1. The usual arithmetic conversions are performed on the operands.

    2. The result of the binary * operator is the product of the operands.

    3. The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

    4. When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded [1]. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

    [1]: This is often called "truncation toward zero".

提交回复
热议问题