数组索引超出范围异常C#

时间:2015-10-13 11:03:53

标签: c# arrays average

我试图在数组的平均值上找到数组中最接近的数字。阵列将在主程序中确定。这是当前的代码:

public static void Main()
{
    double[] numbers = { 1, 2, 3, 2, 5 };    
    double m1 = Miidi(numbers);         
    double m2 = Miidi(new double[] { 1 });  
    double m3 = Miidi(new double[] { 3, 3 });
    double m4 = Miidi(new double[] { });
    Console.WriteLine(m1);
    Console.WriteLine(m2);
    Console.WriteLine(m3);
    Console.WriteLine(m4);
}

public static double Miidi(double[] numbers)
{
    double average = 0;
    average = numbers.Average();

    double nearest = FindNearest(numbers, average);
    return nearest;
}

public static double FindNearest(double[] t, double avg)
{
    double searchValue = avg;
    double currentNearest = t[0];
    double currentDiff = currentNearest - searchValue;

    for (int i = 0; i < t.Length; i++)
    {
        double diff = t[i] - avg;
        if (diff < currentDiff)
        {
            currentDiff = diff;
            currentNearest = t[i];
        }
    }
    return currentNearest;
}

}

我的数组索引超出了范围异常。我尝试了你们提供的方法并将&lt; =更改为&lt;在循环中,但我仍然得到例外。我提供了主要程序以便澄清。

2 个答案:

答案 0 :(得分:2)

除了我的评论:

数组/集合始终从0开始。

e.g。

t[0] = 1;
t[1] = 2;
t[2] = 3;
t[3] = 4;

如果你像这样循环t

for(int i = 0; i <= t.Length; i++)

然后i将计算以下内容:

0
1
2
3
4

因为t.Length = 4而您说i less than equal 4

但是由于数组从0开始,i可能不会大于3,否则会抛出IndexOutOfRangeExcepiton

如果您将循环更改为

for (int i = 0; i < t.Length; i++)

它会毫无例外地完成,因为i现在不会大于3。

<强>更新

除了你的评论之外:

将空数组传递给方法Miidi()。只需检查数组中是否有任何项目:

public static double Miidi(double[] numbers)
{
    if (numbers != null && numbers.Length > 0)
    {
        double average = 0;
        average = numbers.Average();

        double nearest = FindNearest(numbers, average);
        return nearest;
    }

    return 0;
}

答案 1 :(得分:1)

更改你的for循环

for (int i = 0; i <= t.Length; i++)

作为

for (int i = 0; i <= t.Length - 1; i++)

因为数组从0开始