【问题标题】:Calculating Averages Throws an "System.IndexOutOfRangeException" Exception计算平均值会引发“System.IndexOutOfRangeException”异常
【发布时间】:2016-11-14 15:55:58
【问题描述】:

我正在尝试编写一个黄金勘探程序,该程序采用 2D 数组形式的初始数据地图,然后生成一张地图,上面标有所有可能的黄金地点。

但是,在计算平均值以确定是否标记探矿点时,我收到“System.IndexOutOfRangeException”异常,程序中断。我将如何解决这个问题?提前感谢您的帮助。

for (int i = 1; i < nRows; i++)
        {
            for (int j = 1; j < nCols - 1; j++)
            {
                //it is at the line below where the program breaks
                double average = (data[i - 1, j] + data[i + 1, j] + data[i, j - 1] + data[i, j + 1]) / 4;


                if (data[i, j] > average)
                {
                    map[i, j] = "*";
                }
            }
        }

【问题讨论】:

  • 你确定标签 C 适合这个问题吗? C 没有异常
  • 是的,那是我的错,我还在习惯美式键盘,所以我按了 Enter 键,以为我在按哈希键。
  • data[i + 1, j] 很可能在外部循环末尾的i == nRows - 1 超出范围。
  • data[i + 1, j] 将抛出i 循环的最后一次迭代。

标签: c# arrays visual-studio exception


【解决方案1】:

您超出了二维数组的边界。所以更改这部分代码:

for (int i = 1; i < nRows; i++)
    {
        for (int j = 1; j < nCols - 1; j++)

for (int i = 1; i < nRows - 2; i++)                  // NOT from 0 to nRows - 1
    {
        for (int j = 1; j < nCols - 2; j++)          // NOT from 0 to nCols - 1

所以你省略了边框。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 2012-06-19
    • 1970-01-01
    相关资源
    最近更新 更多