0

I faced the error mentioned in the title when doing my homework, and simply can't find a way to remove it. Here is the method that I have this problem with:

public static double LaskeMiidi(double[] luvut)
{
    double ka = Keskiarvo(luvut);
    double miidi = luvut[0];

    for (int i = 0; i < luvut.Length; i++)
    {
        if (luvut[i] - ka < luvut[i + 1] - ka) // The line error points to!
        {
            miidi = luvut[i];
        }
        else
        {
            miidi = luvut[i + 1];
        }
    }
    return miidi;
}

So basically the problem is that when I say luvut[i + 1], at some point this index might become more than the length of the array is. I just can't figure out any ways to solve this problem, since I'm only a beginner with programming.

4

4 回答 4

2

是的,这就是问题所在:

for (int i = 0; i < luvut.Length; i++)
{
    if (luvut[i] - ka < luvut[i + 1] - ka)

什么时候iluvut.Length - 1,那么i + 1将是luvut.Length- 因此是一个无效的索引。(对于 length 数组x,有效索引0x - 1包含在内。)您可能希望提前结束一次迭代:

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

这种方式i + 1仍然是数组中的有效索引 - 无论是在条件中还是在子句if的主体中。else

于 2013-10-15T21:21:05.830 回答
0

请注意,当您定义一个数组时,项目范围在 0 和array.length-1. 所以你应该写:

for (int i = 0; i < luvut.Length-1; i++)
于 2013-10-15T21:30:16.007 回答
0

i = luvut.Length -1,luvut[i + 1]超出数组边界时会出错。

您需要:

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

或者luvut[i + 1]在另一个 If 块中以另一种方式处理问题。

于 2013-10-15T21:31:24.837 回答
0

提前结束循环:

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

这会阻止循环到达索引无效的点。

于 2013-10-15T21:21:58.817 回答