c# - 如何在 C# 中获取模数?

标签 c# modulus

<分区>

长话短说:

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 mod 5。余数运算符适用于正数,但不适用于负数。

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

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/

相关文章:

python - 使用模数/百分号格式化字符串

java - 为什么 % 向上舍入

python - 在 python 条件语句中使用模数运算符

c# - 关闭 Word 文档时出错 : "The message filter indicated that the application is busy."

c# - 如何调整/控制已实现和发布的 WPF 应用程序的高度

c# - 在参数化 OleDbCommand 中使用 DateTime 时出现异常

c++ - 根据用户输入计算尽可能少的硬币

c# - ZXing-Core BitMatrix转BitMap

c# - 如何以功能方式获取中间金额列表?使用 LINQ?

基于除法的 Javascript 余数不正确