使Java模数的行为与负数一样的最佳方法是什么? [英] Best way to make Java's modulus behave like it should with negative numbers?

查看:146
本文介绍了使Java模数的行为与负数一样的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在你做的时候

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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆