Mod with negative numbers gives a negative result in Java and C
问题 Let's say I have (-5) mod 8 . I tried it in both languages Java and C, and they gave me a -5 result when I was expecting 3 . Why is this happening? Can a modulus be negative? And what should I change to get the correct result? Java code public class Example { public static void main(String[] args) { int x; x = -5%8; System.out.println(x); } } C code int main(){ int x; x = -5%8; printf("%d", x); } OUTPUTS 回答1: The % operator is treated as a remainder operator, so the sign of the result is the