[英]run time error:index out of range exception was unhandled
在下面的代码中,我想实现floyd算法,用户在文本框中输入一些数字,输出应该是从节点i到节点j的最短距离。但是当我输入例如4的数字时,它将给出运行时错误:我在下面评论的行上超出了范围,并对其进行了调试,我明白k,i仅取1个值,并且不取小于n + 1的另一个值,但是j可以取小于n + 1的所有值,这我能解决这个问题吗?
编辑:感谢您的回答,我更正了
private void button10_Click(object sender, EventArgs e)
{
string ab = textBox11.Text;
int matrixDimention = Convert.ToInt32(ab);
int[,] intValues = new int[matrixDimention, matrixDimention];
string[] splitValues = textBox9.Text.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i / (matrixDimention), i % (matrixDimention)] = Convert.ToInt32(splitValues[i]);
string displayString = "";
for (int inner = 0; inner < intValues.GetLength(0); inner++)
{
for (int outer = 0; outer < intValues.GetLength(0); outer++)
displayString += String.Format("{0}\t", intValues[inner, outer]);
displayString += Environment.NewLine;
}
int n=matrixDimension
MessageBox.Show("matrix"+strn+ "in" + strn + "is\n\n\n" +displayString);
////before this line i wrote the codes to get the numbers that user enter in textbox and put it in an 2d array
for (int k = 0; k < n; k++)/// k just take 1 in debugging!!!
for (int i = 0; i < n; i++)///i just take 1 in debugging!!!
for (int j = 0; j < n; j++)///j took the values true
/*i took that error on this line */ if (intValues[i, j] > intValues[i, k] + intValues[k, j])
{
intValues[i, j] = intValues[i, k] + intValues[k, j];
string str_intvalues = intValues[i, j].ToString();
MessageBox.Show("Shortest Path from i to j is: " + str_intvalues);
}
else
{
string str_intvalues = intValues[i, j].ToString();
MessageBox.Show("Shortest Path from i to j is: " + str_intvalues);
}
}
大多数编程语言(包括C#)都从位置0开始计数数组单元。
这意味着,如果您有一个大小为N的数组,则索引的范围为0到N-1。
因此,所有循环应如下所示:
for (int j = 0; j < n; j++)
而且,当我再次查看代码时,我意识到您intValues
是一个二维矩阵,每边的大小为matrixDimention
。 但是n
的大小为(int)Math.Pow(matrixDimention,2)。
因此,如果您尝试在k传递matrixDimention
时访问intValues
, matrixDimention
超出范围。
您的matrixDimention用于初始化intValues,但是您使用int n = (int)Math.Pow(matrixDimention, 2);
为了遍历矩阵,您应该只在for循环中使用matrixDimention:
for (int k = 0; k < matrixDimention; k++)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.