我試圖做一個程序,它加總了數組中的元素。但我有'System.IndexOutOfRangeException'MVS上的錯誤。有人可以告訴我的錯誤在哪裏嗎?C#二維詮釋數組,總結所有元素
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'是4,而不是2.您必須使用'GetLength'來獲取每個維度的長度。 – juharr