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

C# 索引在while循环内数组异常的边界之外,c#,math,primes,C#,Math,Primes,例外情况: 索引超出了数组的边界 在下面的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 o

例外情况:

索引超出了数组的边界

在下面的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;
}
我看过VisualStudio调试器,它说cprome是一个疯狂的负数,长度是0,但不应该是

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

调用此代码的代码如下所示,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)
索引是零基,这意味着从零开始,但长度不是这样
因此,您总是有一个超出数组长度的循环周期。

您的数组的长度为
长度,但您在循环中运行
长度+1次。顺便说一下,永远不要使用
Goto