配列の要素を合計するプログラムを作成しようとしました。しかし、私は '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();
}
を使用することができます。この場合、 'Length'は4ではなく2です。各次元の長さを取得するには' GetLength'を使う必要があります。 – juharr