简体   繁体   English

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

[英]Array Index out of range exception C#

I'm trying to find the closest number in an array when compared to the array's average. 与数组的平均值相比,我正在尝试查找数组中最接近的数字。 The array will be determined in the main program. 该数组将在主程序中确定。 Here's the current code: 这是当前代码:

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;
}

} }

I'm getting an array index out of range exception. 我收到数组索引超出范围异常。 I tried the methods you guys provided and changed the <= to < in the loop, but I'm still getting the exception. 我尝试了你们提供的方法,并在循环中将<=更改为<,但是我仍然遇到异常。 I provided the main program for clarification. 我提供了主程序进行说明。

Additional to my comment: 除了我的评论:

An array/collection starts always at 0. 数组/集合始终从0开始。

eg 例如

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

If you loop t like this: 如果您像这样循环t

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

then i will count the following: 那么i将数以下各项:

0
1
2
3
4

because t.Length = 4 and you say i less than equal 4 . 因为t.Length = 4并且您说i less than equal 4

But since an array starts at 0, i may not be greater than 3, otherwise it will throw an IndexOutOfRangeExcepiton . 但是由于数组从0开始,所以i不能大于3,否则它将抛出IndexOutOfRangeExcepiton

If you change your loop to 如果将循环更改为

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

it will finish without any exception, because i wont be greater than 3 now. 它会毫无例外地结束,因为i现在不会大于3。

UPDATE: 更新:

Additional to your comments: 除了您的评论:

You pass an empty array to your method Miidi() . 您将一个空数组传递给方法Miidi() Just check if there are any items in the array: 只需检查数组中是否有任何项目:

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;
}

Change your for loop 更改您的for循环

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

as

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

because an Array starts at 0 因为数组从0开始

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM