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
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)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           4507 次  |  
        
|   最近记录:  |