# Java 中的模數

## Java 中使用 `Math.floorMod()` 計算兩個數的模數

`Math.floorMod(a,b)` 函式接受兩個可以是 int 或 long 型別的引數。在函式中，`a` 是被除數，而 b 是除數。它返回傳遞給函式的兩個引數的下限模數。say `a``b` 的 mod 將產生大於或等於 0 且小於 b 的結果。

``````import java.lang.Math;

public class Main {
public static void main(String[] args) {
int num1 = 20, num2 = 4;
System.out.println(Math.floorMod(num1, num2));

int num3 = 113, num4 = 30;
System.out.println(Math.floorMod(num3, num4));

int num5 = 113, num6 = -30;
System.out.println(Math.floorMod(num5, num6));

int num7 = -113, num8 = 30;
System.out.println(Math.floorMod(num7, num8));
}
}
``````

``````0
23
-7
7
``````

## Java 中使用`%`運算子計算兩個數的模數

``````public class ModTest {
public static void main(String args[]) {
int num1 = 17;
int num2 = 2;

boolean result = false;

if (result = (num1 % num2) == 0) {
System.out.println("Number " + num1 + " is even");
} else {
System.out.println("Number " + num1 + " is odd");
}

int num3 = -23;
int num4 = -3;
System.out.println("Remainder1: " + num3 % num2);
System.out.println("Remainder2: " + num1 % num4);
}
}
``````

``````Number 17 is odd
Remainder1: -1
Remainder2: 2
``````

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.