使 Java 的模数表现得像负数一样的最佳方法? [英] Best way to make Java's modulus behave like it should with negative numbers?
问题描述
在java中当你这样做
In java when you do
a % b
如果 a 是负数,它将返回一个负结果,而不是像它应该的那样环绕到 b.解决此问题的最佳方法是什么?我唯一能想到的就是
If a is negative, it will return a negative result, instead of wrapping around to b like it should. What's the best way to fix this? Only way I can think is
a < 0 ? b + a : a % b
推荐答案
它的行为应该是 a % b = a - a/b * b;即它是余数.
It behaves as it should a % b = a - a / b * b; i.e. it's the remainder.
你可以做 (a % b + b) % b
You can do (a % b + b) % b
这个表达式的作用是(a % b)
的结果必然低于b
,无论a
是正数还是负数.添加 b
处理 a
的负值,因为 (a % b)
是 -b之间的负值code>和
0
,(a % b + b)
必然低于b
而为正.最后一个模数是在 a
开始时为正数的情况下存在的,因为如果 a
是正数 (a % b + b)
会变大比 b
.因此, (a % b + b) % b
再次将其变成小于 b
(并且不会影响负的 a
值).
This expression works as the result of (a % b)
is necessarily lower than b
, no matter if a
is positive or negative. Adding b
takes care of the negative values of a
, since (a % b)
is a negative value between -b
and 0
, (a % b + b)
is necessarily lower than b
and positive. The last modulo is there in case a
was positive to begin with, since if a
is positive (a % b + b)
would become larger than b
. Therefore, (a % b + b) % b
turns it into smaller than b
again (and doesn't affect negative a
values).
这篇关于使 Java 的模数表现得像负数一样的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!