2016-07-08 3 views
2

配列の要素を合計するプログラムを作成しようとしました。しかし、私は 'System.IndexOutOfRangeException' MVSの間違いがあります。誰かが私のミスがどこにあるかを伝えることができますか?C#2次元のint配列、すべての要素の合計を外します

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

または '().Sum()'をキャストします。タイプを確認する必要はありません –

+0

おかげでたくさんの... – Shopska

6

あなたは各次元の長さを取得する必要があります(2次元配列の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