我试图制作一个对数组元素进行求和的程序。但是我在MVS上有' System.IndexOutOfRangeException '错误。有人可以告诉我我的错误在哪里吗?
public static int Sum(int[,] arr)
{
int total = 0;
for (int i = 0; i <= arr.Length; i++)
{
for (int j = 0; j <= arr.Length; j++)
{
total += arr[i,j];
}
}
return total;
}
static void Main(string[] args)
{
int[,] arr = { { 1, 3 }, { 0, -11 } };
int total = Sum(arr);
Console.WriteLine(total);
Console.ReadKey();
}
您必须获取每个维度的长度(Length
2D数组的属性是数组中项目的总数),比较结果应为<
,而不是<=
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
total += arr[i,j];
}
}
另外,您也可以使用foreach
循环
foreach (int item in arr)
{
total += item;
}
甚至Linq
int total = arr.Cast<int>().Sum();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句