What's the syntax for mod in java

2019-01-02 17:16发布

As an example in pseudocode:

if ((a mod 2) == 0)
{
    isEven = true;
}
else
{
    isEven = false;
}

标签: java modulo
15条回答
伤终究还是伤i
2楼-- · 2019-01-02 17:51

In Java it is the % operator: 15.17.3. Remainder Operator %

Note that there is also floorMod in the java.lang.Math class which will give a different result from % for arguments with different signs:

public static int floorMod​(int x, int y)

查看更多
何处买醉
3楼-- · 2019-01-02 17:53

While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.

(a % b + b) % b

This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.

Note: If b is negative, the result will also be negative

查看更多
只若初见
4楼-- · 2019-01-02 17:53
if (a % 2 == 0) {
} else {
}
查看更多
不流泪的眼
5楼-- · 2019-01-02 17:54

Also, mod can be used like this:

int a = 7;
b = a % 2;

b would equal 1. Because 7 % 2 = 1.

查看更多
何处买醉
6楼-- · 2019-01-02 17:54

The remainder operator in Java is % and the modulo operator can be expressed as

public int mod(int i, int j)
{
  int rem = i % j;
  if (j < 0 && rem > 0)
  {
    return rem + j;
  }
  if (j > 0 && rem < 0)
  {
    return rem + j;
  }
  return rem;
}
查看更多
琉璃瓶的回忆
7楼-- · 2019-01-02 17:56

Java actually has no modulo operator the way C does. % in Java is a remainder operator. On positive integers, it works exactly like modulo, but it works differently on negative integers and, unlike modulo, can work with floating point numbers as well. Still, it's rare to use % on anything but positive integers, so if you want to call it a modulo, then feel free!

查看更多
登录 后发表回答