Modulo operation with negative numbers

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

    C99 requires that when a/b is representable:

    (a/b) * b + a%b shall equal a

    This makes sense, logically. Right?

    Let's see what this leads to:


    Example A. 5/(-3) is -1

    => (-1) * (-3) + 5%(-3) = 5

    This can only happen if 5%(-3) is 2.


    Example B. (-5)/3 is -1

    => (-1) * 3 + (-5)%3 = -5

    This can only happen if (-5)%3 is -2

提交回复
热议问题