C#二维int数组,将所有元素相加 [英] C # Two-dimensional int array,Sum off all elements
本文介绍了C#二维int数组,将所有元素相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图制作一个程序,对数组中的元素求和。但是我在MVS上有 System.IndexOutOfRangeException 错误。有人可以告诉我我的错误在哪里吗?
I tried to make a program which sums the elements in an array. But I have 'System.IndexOutOfRangeException' mistake on MVS. Can somebody tell where is my mistake?
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
属性是数组中项目的总数),并且比较值应为<
,而不是< =
You have to get the length of each dimension (the Length
property of a 2D array is the total number of items in the array) and the comparison should be <
, not <=
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
total += arr[i,j];
}
}
或者,您也可以使用 foreach
循环
Alternatively you can just use a foreach
loop
foreach (int item in arr)
{
total += item;
}
甚至是Linq
int total = arr.Cast<int>().Sum();
这篇关于C#二维int数组,将所有元素相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文