Mod with negative numbers gives a negative result in Java and C

Joh*_*ohn 0 c java math mod

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

C code

int main(){
    int x;
    x = -5%8;
    printf("%d", x);
}
Run Code Online (Sandbox Code Playgroud)

OUTPUTS

在此处输入图片说明

Sus*_*ger 6

The % operator is treated as a remainder operator, so the sign of the result is the same as that of the dividend.

If you want a modulo function, you can do something like this:

int mod(int a, int b)
{
    int ret = a % b;
    if (ret < 0)
        ret += b;
    return ret;
}
Run Code Online (Sandbox Code Playgroud)