This question already has answers here:
Mod of negative number is melting my brain
                                
                                    (11个答案)
                                
                        
                                2年前关闭。
            
                    
TL; DR:

int remainder = -1 % 5; //-1
int modulus = -1 modulus 5; //4 How do I do this?




我正在尝试读取数组的调制值。因此,由数组长度调制的索引将是更新的索引。例如:

array = {100, 200, 300, 400, 500}
array[6] = array[6 mod 5] = array[1] = 200


很简单。但是,当我的指数为负数时,我就会遇到麻烦。

array[-1] = array[???] = array[4] = 500


我不知道如何执行-1 mod5。余数运算符对正数有效,但对负数无效。

这是我的示例代码,仅适用于正值:

static void Main(string[] args)
{
    int[] myArray = new int[5] { 100, 200, 300, 400, 500 };
    int myIndex = myArray.Length - 1;
    for (int i = 0; i < 15; i++)
    {
        myIndex = --myIndex % myArray.Length;
        Console.WriteLine("Value: " + myArray[myIndex]);
    }
    Console.WriteLine("Done");
}


如何获取数字的模数,而不是C#中的余数?

最佳答案

我认为您想要实现的是:

var newIndex = myIndex % myArray.Length;
if (newIndex < 0)
{
    newIndex += myArray.Length;
}


它能满足您的要求吗?

您对“模数”的使用也使我感到困惑。据我所知,模量是一个绝对值。为了得到它,只需使用

var modulus = Math.Abs(value)

关于c# - 如何获取C#中的模数? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45043383/

10-10 13:01