索引在 while 循环内的数组异常的边界之外

Index was outside the bounds of the array exception inside while loop

异常:

Index was outside the bounds of the array

在下面的 if 或下面的 else 中被抛出

 public static Int64[] PrimeGenerator(Int64 length = 1)
{
    Int64 pos = 0;
    Int64[] primes = new Int64[length];
    Int64 Cprime = 2;
    Int64 controller = 0;//On evens it adds one less than, on odds it adds oone more than
    while(length >= 0)
    {
        if(pos == 0)
        {
            primes[pos] = 2;
            goto End;
        }
        if(controller % 2 == 0)
        {
            primes[pos] = (2 * Cprime - 1);
        }
        else
        {
            primes[pos] = (2 * Cprime + 1);
        }
        End:
        Cprime = primes[pos];
        controller++;
        pos++;
        length--;
    }
    return primes;
}

我查看了 visual studio 调试器,它说 Cprime 是一个疯狂的负数,长度为 0,但它不应该是

当我将所有 Int64 更改为 UInt64 时,Cprime 是一些疯狂的正整数并且长度仍然为零

调用这段代码的代码是这样的,print是重命名的Console.WriteLine

static void Main()
{
    UInt64 p = 1000;
    UInt64[] primes = PrimeGenerator(p);
    bool[] truth = BadArrayTest(primes);
    foreach(bool tru in truth)
    {
        print(tru);
    }
    System.Threading.Thread.Sleep(50000);
    Environment.Exit(0);
}

就这样做

while(length > 0)

索引是零基,意思是从零开始,但长度不是这样的 所以你总是有一个超出数组长度的循环。

你的数组是 length,但你 运行 循环了 length+1 次。顺便说一下,永远不要使用 Goto.