负数的mod正在融化我的大脑 [英] Mod of negative number is melting my brain
问题描述
我试图mod的一个整数得到一个数组的位置,这样它会循环圆。做 I%
工作正常,正数,但对于负数这一切都错了。
arrayLength
I'm trying to mod an integer to get an array position so that it will loop round. Doing i %
arrayLength
works fine for positive numbers but for negative numbers it all goes wrong.
4 % 3 == 1
3 % 3 == 0
2 % 3 == 2
1 % 3 == 1
0 % 3 == 0
-1 % 3 == -1
-2 % 3 == -2
-3 % 3 == 0
-4 % 3 == -1
所以我需要的实现。
so i need an implementation of
int GetArrayIndex(int i, int arrayLength)
这样
GetArrayIndex( 4, 3) == 1
GetArrayIndex( 3, 3) == 0
GetArrayIndex( 2, 3) == 2
GetArrayIndex( 1, 3) == 1
GetArrayIndex( 0, 3) == 0
GetArrayIndex(-1, 3) == 2
GetArrayIndex(-2, 3) == 1
GetArrayIndex(-3, 3) == 0
GetArrayIndex(-4, 3) == 2
我以前做了这一点,但由于某种原因,今天是融化我的大脑:(
I've done this before but for some reason it's melting my brain today :(
推荐答案
我总是用我自己的 MOD
函数,定义为
I always use my own mod
function, defined as
int mod(int x, int m) {
return (x%m + m)%m;
}
当然,如果你不屑大鱼大肉的两个的调用模操作,你可以把它写成
Of course, if you're bothered about having two calls to the modulus operation, you could write it as
int mod(int x, int m) {
int r = x%m;
return r<0 ? r+m : r;
}
或其变体。
它工作的原因是,×%m为始终在范围[-m + 1,M-1]。所以,如果在所有为负,加米它将把它的正数范围,而不改变其值模M
The reason it works is that "x%m" is always in the range [-m+1, m-1]. So if at all it is negative, adding m to it will put it in the positive range without changing its value modulo m.
这篇关于负数的mod正在融化我的大脑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!