Java 模块化算法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14445952/
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
Java Modular Arithmetic
提问by user1996035
Possible Duplicate:
Mod in Java produces negative numbers
可能的重复:
Java 中的 Mod 产生负数
When I try to print -16 mod 57, I should get 41. However, I keep getting -16 as my answer. What gives?
当我尝试打印 -16 mod 57 时,我应该得到 41。但是,我一直得到 -16 作为我的答案。是什么赋予了?
Here is my code:
这是我的代码:
public class TestMod {
public static void main(String[] args) {
int number = -16;
int mod = 57;
int answer = number%mod;
System.out.println(answer);
}
}
回答by NPE
From the JLS:
从JLS:
The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.
二进制数字提升(第 5.6.2 节)后的整数操作数的余数运算产生的结果值使得 (a/b)*b+(a%b) 等于 a。
Substitute the numbers from your example, and you'll see that -16
is what the language spec mandates.
替换示例中的数字,您会看到这-16
就是语言规范所要求的。
This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0).
It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.
即使在被除数是其类型的最大可能数量级的负整数且除数为 -1(余数为 0)的特殊情况下,该恒等式也成立。
根据这个规则,余数运算的结果只有在被除数为负时才能为负,只有在被除数为正时才能为正。而且,结果的大小总是小于除数的大小。
Here is how you can get the result you're expecting:
以下是获得预期结果的方法:
public static void main(String[] args) {
int number = -16;
int mod = 57;
int answer = ((number % mod) + mod) % mod;
System.out.println(answer);
}
回答by Daniel Fischer
When the first operand is negative, the remainder operator %
returns a negative result. That's common behaviour in many languages.
当第一个操作数为负数时,余数运算符%
返回一个负数结果。这是许多语言中的常见行为。