java中mod的语法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/90238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:10:45  来源:igfitidea点击:

What's the syntax for mod in java

javamodulo

提问by Bob

As an example in pseudocode:

以伪代码为例:

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

采纳答案by Cody Hatch

Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the remainderoperator %. For your exact example:

对于非负整数,您可以使用数运算符,而不是语义略有不同的模运算符%。对于您的确切示例:

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

This can be simplified to a one-liner:

这可以简化为单行:

isEven = (a % 2) == 0;

回答by martinatime

Here is the representation of your pseudo-code in minimal Java code;

这是用最少的 Java 代码表示的伪代码;

boolean isEven = a % 2 == 0;

I'll now break it down into its components. The modulus operator in Java is the percent character (%). Therefore taking an int % int returns another int. The double equals (==) operator is used to compare values, such as a pair of ints and returns a boolean. This is then assigned to the boolean variable 'isEven'. Based on operator precedence the modulus will be evaluated before the comparison.

现在我将把它分解成它的组成部分。Java 中的模运算符是百分比字符 (%)。因此,使用 int % int 会返回另一个 int。双等号 (==) 运算符用于比较值,例如一对整数并返回一个布尔值。然后将其分配给布尔变量“isEven”。根据运算符优先级,将在比较之前评估模数。

回答by jjrv

The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use & (the and operator) like isEven = !( a & 1 ).

模运算符是 %(百分号)。要测试均匀性或通常对 2 的幂进行模运算,您还可以使用 &(和运算符),如 isEven = !( a & 1 )。

回答by J D OConal

if (a % 2 == 0) {
} else {
}

回答by jjnguy

Also, mod can be used like this:

此外,mod 可以这样使用:

int a = 7;
b = a % 2;

bwould equal 1. Because 7 % 2 = 1.

b将等于 1。因为7 % 2 = 1

回答by Jay Bazuzi

An alternative to the code from @Cody:

来自@Cody 的代码的替代方法:

Using the modulus operator:

使用模运算符:

bool isEven = (a % 2) == 0;

I think this is marginally better code than writing if/else, because there is less duplication & unused flexibility. It does require a bit more brain power to examine, but the good naming of isEvencompensates.

我认为这比编写 if/else 稍微好一些,因为重复和未使用的灵活性更少。它确实需要更多的脑力来检查,但好的命名可以isEven弥补。

回答by Greg Charles

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!

Java 实际上没有像 C 那样的模运算符。Java 中的 % 是余数运算符。在正整数上,它的工作方式与模数完全一样,但它在负整数上的工作方式不同,并且与模数不同,它也可以处理浮点数。尽管如此,除了正整数外很少使用 % ,所以如果你想称它为模数,那就随意吧!

回答by Rob Rolnick

Since everyone else already gave the answer, I'll add a bit of additional context. % the "modulus" operator is actually performing the remainder operation. The difference between mod and rem is subtle, but important.

由于其他人已经给出了答案,我将添加一些额外的上下文。% “模数”运算符实际上是在执行余数运算。mod 和 rem 之间的区别很微妙,但很重要。

(-1 mod 2) would normally give 1. More specifically given two integers, X and Y, the operation (X mod Y) tends to return a value in the range [0, Y). Said differently, the modulus of X and Y is always greater than or equal to zero, and less than Y.

(-1 mod 2) 通常会给出 1。更具体地说,给定两个整数 X 和 Y,运算 (X mod Y) 倾向于返回 [0, Y) 范围内的值。换句话说,X 和 Y 的模数总是大于或等于零,并且小于 Y。

Performing the same operation with the "%" or rem operator maintains the sign of the X value. If X is negative you get a result in the range (-Y, 0]. If X is positive you get a result in the range [0, Y).

使用“%”或 rem 运算符执行相同的操作会保持 X 值的符号。如果 X 为负,则得到范围 (-Y, 0] 内的结果。如果 X 为正,则得到范围 [0, Y) 内的结果。

Often this subtle distinction doesn't matter. Going back to your code question, though, there are multiple ways of solving for "evenness".

通常,这种细微的区别并不重要。不过,回到您的代码问题,有多种方法可以解决“均匀性”问题。

The first approach is good for beginners, because it is especially verbose.

第一种方法适合初学者,因为它特别冗长。

// Option 1: Clearest way for beginners
boolean isEven;
if ((a % 2) == 0)
{
  isEven = true
}
else
{
  isEven = false
}

The second approach takes better advantage of the language, and leads to more succinct code. (Don't forget that the == operator returns a boolean.)

第二种方法更好地利用了语言,并导致更简洁的代码。(不要忘记 == 运算符返回一个布尔值。)

// Option 2: Clear, succinct, code
boolean isEven = ((a % 2) == 0);

The third approach is here for completeness, and uses the ternaryoperator. Although the ternary operator is often very useful, in this case I consider the second approach superior.

第三种方法在这里是为了完整性,并使用三元运算符。尽管三元运算符通常非常有用,但在这种情况下,我认为第二种方法更胜一筹。

// Option 3: Ternary operator
boolean isEven = ((a % 2) == 0) ? true : false;

The fourth and final approach is to use knowledge of the binary representation of integers. If the least significant bit is 0 then the number is even. This can be checked using the bitwise-and operator(&). While this approach is the fastest (you are doing simple bit masking instead of division), it is perhaps a little advanced/complicated for a beginner.

第四种也是最后一种方法是使用整数二进制表示的知识。如果最低有效位为 0,则该数字为偶数。这可以使用按位与运算符(&)进行检查。虽然这种方法是最快的(你正在做简单的位掩码而不是除法),但对于初学者来说它可能有点高级/复杂。

// Option 4: Bitwise-and
boolean isEven = ((a & 1) == 0);

Here I used the bitwise-and operator, and represented it in the succinct form shown in option 2. Rewriting it in Option 1's form (and alternatively Option 3's) is left as an exercise to the reader. ;)

在这里,我使用了按位与运算符,并以选项 2 中所示的简洁形式表示它。以选项 1 的形式(或者选项 3 的形式)重写它作为练习留给读者。;)

Hope that helps.

希望有帮助。

回答by Zom-B

To get Java's % (REM) operation to work like MOD for negative X and positive Y values, you can use this method:

要使 Java 的 % (REM) 操作像 MOD 一样对负 X 和正 Y 值起作用,您可以使用以下方法:

private int mod(int x, int y)
{
    int result = x % y;
    if (result < 0)
    {
        result += y;
    }
    return result;
}

or with the ternary operator (shorter, but not possible or less efficient in some situations):

或使用三元运算符(较短,但在某些情况下不可能或效率较低):

private int mod(int x, int y)
{
    int result = x % y;
    return result < 0? result + y : result;
}

回答by eljenso

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

Java中的余数运算符是%,模运算符可以表示为

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;
}