我试图对一个整数进行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

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


当前回答

只需将您的模量(arrayLength)添加到%的负结果,就可以了。

其他回答

单行实现只使用%一次:

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

ShreevatsaR的第二个答案是:

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

可以在新版本的c#中使用var模式和switch表达式作为一行程序来编写:

int mod(int x, int m) => (x % m) switch 
{ 
    < 0 and var r => r + m, var r => r 
}

我总是使用我自己的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的模的值。

对于更注重性能的开发人员

uint wrap(int k, int n) ((uint)k)%n

一个小的性能比较

Modulo: 00:00:07.2661827 ((n%x)+x)%x)
Cast:   00:00:03.2202334 ((uint)k)%n
If:     00:00:13.5378989 ((k %= n) < 0) ? k+n : k

至于浇注到uint的性能成本在这里看一下

mod函数有很多实现,我认为有必要列出所有实现——至少根据维基百科,我相信还有更多。

// Important to be able to use `MathF`.
using System;

public static class MathFUtils {
    public static class Mod {
        public static float Trunc(float a, float b) =>
            a - b * ((int)(a / b));

        public static float Round(float a, float b) =>
            a - b * MathF.Round(a / b);

        public static float Floor(float a, float b) =>
            a - b * MathF.Floor(a / b);

        public static float Ceil(float a, float b) =>
            a - b * MathF.Ceiling(a / b);

        public static float Euclidean(float a, float b) =>
            a - MathF.Abs(b) * MathF.Floor(a / MathF.Abs(b));
    }
}

根据维基百科(以及我的经验),坚持欧几里得。它在数学和概率性质方面是最有用的。如果您需要Trunc,那么我相信%可以做到这一点。

此外,对于那些可能对它们各自做什么以及如何做感到困惑的人,我强烈建议阅读维基百科的文章(即使很难)并查看每个表示的图像。

当然,这些不一定是性能最好的,但它们确实有效。如果你关心性能,我建议你找一个本地的c#之神,或者在他们经过我们的尘世时问他。