-1

第一篇文章。我试图将大量数字放入一个数组(-1000 到 1000)中,然后进行指数搜索。我对 c# 的经验很少,并且在如何将如此大的范围放入数组中陷入困境。我一直在尝试 for 循环,但被卡住了。

int[] rangeArray = new int [2000];
            for(int x = -1000; x < 1000; ++x)
            {
                rangeArray[x + 1000] = x;
            }
4

1 回答 1

2

您可以Enumerable.Range为此使用:

int[] numbers = Enumerable.Range(-1000, 2001).ToArray();

第一个变量是“start”,第二个是“count”。

结果是第一项的值为 -1000,最后一项的值为 1000。

使用循环的替代方法:

int[] values = new int[2001];

for (int i = -1000; i <= 1000; ++i)
{
    values[i+1000] = i; // since arrays start at 0, we have to add 1000 to ensure the first item gets puts in 0, and the last in 2000.
}
于 2020-04-03T03:05:16.323 回答