在 C# 中对交错 int 数组求和

本文关键字:int 数组 求和 | 更新日期: 2023-09-27 17:56:54

在这里做:C#二维int数组,对所有元素求和,但这次用交错数组。获取:

System.IndexOutOfRangeException.

我是一个寻求帮助的初学者。这是我的代码:

public static int Sum(int[][] arr) 
{
    int total = 0;
    for (int i = 0; i < arr.GetLength(0); i++)
    {
         for (int j = 0; j < arr.GetLength(1); j++) 
         { 
              total += arr[i][j];
         }
    } 
    return total; 
}
static void Main(string[] args)
{
     int[][] arr = new int[][] 
     {
          new int [] {1},
          new int [] {1,3,-5},
     };
     int total = Sum(arr);
     Console.WriteLine();
     Console.ReadKey();    
}

在 C# 中对交错 int 数组求和

在你的内部循环中,改为这样做:

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i] != null)
    {
        for (int j = 0; j < arr[i].Length; j++) 
        { 
            total += arr[i][j];
        }  
    }
} 
return total; 

因为你的列表甚至没有在第一个维度的arr.GetLength(1)上得到例外 - 它在那个地方没有项目。

如果

数组如下所示,则需要if (arr[i] != null)行:

 int[][] arr = new int[][] 
 {
      new int [] {1},
      null,
      new int [] {1,3,-5},
 };

在这种情况下,当我们循环i==1并尝试执行arr[i].Length(意味着arr[1].Length时,我们将收到一个 NullReferenceException .


在完成基础知识并进入 Linq 之后,您当前的所有Sum方法都可以替换为:

arr.SelectMany(item => item).Sum()

但最好从基础知识开始:)

由于您使用的是交错数组,因此该数组的维度不一定是均匀的。看看那个交错数组的初始化代码:

int[][] arr = new int[][] {
    new int [] {1},
    new int [] {1,3,-5},
};

所以在第一维中,有两个元素({1}{1, 3, -5})。但第二个维度的长度不同。第一个元素只有一个元素({1}),而第二个元素有3个元素({1, 3, -5})。这就是为什么你面对IndexOutOfRangeException.

要解决此问题,您必须将内部循环调整为该维度的元素数量。你可以这样做:

for (int i = 0; i < arr.Length; i++) {
    for (int j = 0; j < arr[i].Length; j++) { 
        total += arr[i][j];
    }  
}