Modulo operation with negative numbers

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

    The other answers have explained in C99 or later, division of integers involving negative operands always truncate towards zero.

    Note that, in C89, whether the result round upward or downward is implementation-defined. Because (a/b) * b + a%b equals a in all standards, the result of % involving negative operands is also implementation-defined in C89.

提交回复
热议问题