2016-07-08 42 views
2

我試圖做一個程序,它加總了數組中的元素。但我有'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(); 
} 

回答

0

問題是你的迴路檢查< =,他們應該是< 由於他們是零個數組索引,檢查< = arr.Length總是會導致索引超出範圍異常。

+1

這只是問題的一半。在這種情況下,'Length'是4,而不是2.您必須使用'GetLength'來獲取每個維度的長度。 – juharr

5

嘗試的LINQ

int[,] arr = { { 1, 3 }, { 0, -11 } }; 

    int total = arr.OfType<int>().Sum(); 

非LINQ的解決方案:

int total = 0; 

    foreach (var item in arr) 
    total += item; 
+1

或'Cast ().Sum()'。無需檢查類型 –

+0

非常感謝... – Shopska

6

你必須讓每個維度的長度(一個二維數組的Length屬性是項目的總數陣列),比較應該是<,而不是<=

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(); 
+0

非常感謝... – Shopska