Modulo operation with negative numbers
问题 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, z); gave me output as (2, -2 , -2) in gcc . I was expecting a positive result every time. Can a modulus be negative? Can anybody explain this behavior? 回答1: 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%(