小编Joh*_*ohn的帖子

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

C code

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

c java math mod

0
推荐指数
1
解决办法
4507
查看次数

标签 统计

c ×1

java ×1

math ×1

mod ×1