我试图对一个整数进行mod以获得一个数组位置,这样它就会循环。做i % arrayLength适用于正数,但对于负数就完全出错了。

 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

我需要一个实现

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

我以前也这么做过,但不知为何,今天我的脑子都要融化了:(


当前回答

这是我对正整数的一行代码,基于这个答案:

用法:

(-7).Mod(3); // returns 2

实现:

static int Mod(this int a, int n) => (((a %= n) < 0) ? n : 0) + a;

其他回答

单行实现只使用%一次:

int mod(int k, int n) {  return ((k %= n) < 0) ? k+n : k;  }

dcastro的答案的单行实现(与其他语言最兼容):

int Mod(int a, int n)
{
    return (((a %= n) < 0) && n > 0) || (a > 0 && n < 0) ? a + n : a;
}

如果你想保留%操作符的使用(在c#中你不能重载本机操作符):

public class IntM
{
    private int _value;

    private IntM(int value)
    {
        _value = value;
    }

    private static int Mod(int a, int n)
    {
        return (((a %= n) < 0) && n > 0) || (a > 0 && n < 0) ? a + n : a;
    }

    public static implicit operator int(IntM i) => i._value;
    public static implicit operator IntM(int i) => new IntM(i);
    public static int operator %(IntM a, int n) => Mod(a, n);
    public static int operator %(int a, IntM n) => Mod(a, n);
}

用例,两者都适用:

int r = (IntM)a % n;

// Or
int r = a % n(IntM);

我总是使用我自己的mod函数,定义为

int mod(int x, int m) {
    return (x%m + m)%m;
}

当然,如果你不介意对模运算进行两次调用,你可以把它写成

int mod(int x, int m) {
    int r = x%m;
    return r<0 ? r+m : r;
}

或其变体。

它起作用的原因是“x%m”总是在[-m+1, m-1]的范围内。所以如果它是负的,加上m就会使它在正范围内而不改变它对m的模的值。

我喜欢Peter N Lewis在这篇文章中提出的技巧:“如果N有一个有限的范围,那么你可以通过添加一个已知的常数倍数(除数)来得到你想要的结果,这个倍数大于最小值的绝对值。”

如果我有一个以度数为单位的值d,我想取

d % 180f

我想避免d为负时的问题,那么我就这样做:

(d + 720f) % 180f

这里假设d可能是负数,但已知它永远不会大于-720。

您期望的行为与c#中%操作符的记录行为相反——可能是因为您期望它以一种在您更习惯的另一种语言中工作的方式工作。c#状态的文档(重点是我的):

对于整数类型的操作数,a % b的结果是a - (a / b) * b产生的值。非零余数的符号与左操作数的符号相同

你想要的值可以通过一个额外的步骤来计算:

int GetArrayIndex(int i, int arrayLength){
    int mod = i % arrayLength;
    return (mod>=0) : mod ? mod + arrayLength;
}