Modulo operation with negative numbers

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

    In Mathematics, where these conventions stem from, there is no assertion that modulo arithmetic should yield a positive result.

    Eg.

    1 mod 5 = 1, but it can also equal -4. That is, 1/5 yields a remainder 1 from 0 or -4 from 5. (Both factors of 5)

    Similarly, -1 mod 5 = -1, but it can also equal 4. That is, -1/5 yields a remainder -1 from 0 or 4 from -5. (Both factors of 5)

    For further reading look into equivalence classes in Mathematics.

提交回复
热议问题