# Java 中負數的模

Joel Swapnil Singh 2023年10月12日

## 在 Java 中使用 `%` 運算子獲取負數的模

``````public class Main {
public static void main(String args[]) {
int x = -4;
int y = 3;
int res = x % y;
System.out.println("Mod value before operation = " + res);
while (x < 0) x += y;
int mod_res = x % y;
System.out.println("Mod value after operation = " + mod_res);
}
}
``````

``````Mod value before operation = -1
Mod value after operation = 2
``````

## 使用 `floormod()` 方法獲取負數的模

``````floorMod(number, mod)
``````

``````public class Main {
public static void main(String args[]) {
int x = -4;
int y = 3;
int res = x % y;
System.out.println("Mod value before operation = " + res);
int mod_res = Math.floorMod(
x, y); // This will have the output value as positive since the smod factor is positive
System.out.println("Mod value after operation having mod factor as positive = " + mod_res);
x = 4;
y = -3;
mod_res = Math.floorMod(
x, y); // This will have the output value as negative since the mod factor is negative
System.out.println("Mod value after operation having mod factor as negative = " + mod_res);
}
}
``````

``````Mod value before operation = -1
Mod value after operation having mod factor as positive = 2
Mod value after operation having mod factor as negative = -2
``````

## 使用 `Math.abs()` 方法獲取負數的 Mod

``````public class Main {
public static void main(String args[]) {
int x = -4;
int y = 3;
int res = x % y;
System.out.println("Mod value before operation = " + res);
int mod_res = (x < 0) ? (y - (Math.abs(x) % y)) % y : (x % y);
System.out.println("Mod value after operation = " + mod_res);
}
}
``````

``````Mod value before operation = -1
Mod value after operation = 2
``````