我尝试编写一个程序来对数组中的元素求和。但我有 '系统索引超出范围异常' MVS 上的错误。有人能告诉我我的错误在哪里吗?
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
二维数组的属性是数组中项目的总数)并且比较应该是<
, not <=
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
total += arr[i,j];
}
}
或者你可以只使用foreach
loop
foreach (int item in arr)
{
total += item;
}
甚至 Linq
int total = arr.Cast<int>().Sum();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)