Modulo operation with negative numbers

前端 未结 12 1631
旧巷少年郎
旧巷少年郎 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:31

    The % operator in C is not the modulo operator but the remainder operator.

    Modulo and remainder operators differ with respect to negative values.

    With a remainder operator, the sign of the result is the same as the sign of the dividend while with a modulo operator the sign of the result is the same as the divisor.

    C defines the % operation for a % b as:

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

    with / the integer division with truncation towards 0. That's the truncation that is done towards 0 (and not towards negative inifinity) that defines the % as a remainder operator rather than a modulo operator.

提交回复
热议问题