【问题标题】:Summing a jagged int array in C#在 C# 中对锯齿状 int 数组求和
【发布时间】:2016-07-13 07:20:12
【问题描述】:

在这里完成:C # Two-dimensional int array,Sum off all elements,但这次使用的是锯齿状数组。获取:

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();    
}

【问题讨论】:

  • 请按照约定规则格式化您的代码。例如在 Visual Studio 中使用 Ctrk+K+D。阅读您的代码真的很不愉快)。阅读更多:msdn.microsoft.com/en-us/library/ff926074.aspx
  • @GiladGreen - 感谢您的回答。程序正在运行。但输出显示空白
  • @Shopska - 您需要将总数添加到WriteLine
  • @GiladGreen 感谢您的好意消息哈哈。请问您,当我添加时,“khlr”答案有什么不同; ' 如果 (arr[i] != null) '?你能解释一下吗?

标签: c# jagged-arrays


【解决方案1】:

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

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()

但最好从基础开始:)

【讨论】:

  • SelectMany 很聪明。没有它可以做到arr.Sum(item =&gt; item.Sum())。在某些“内部”数组为 null 的情况下,您的解决方案都不起作用。
  • 修复了null 的情况
  • @Shopska - 添加了关于 null 的说明。
【解决方案2】:

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

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];
    }  
} 

【讨论】:

  • 你能说出究竟是什么不起作用吗?当我运行代码时,它可以工作。尽管正如@Gilad 已经指出的那样,您还应该注意NULLs。
  • 对不起,这是我的错误,“Gilad Green”解释了它:)
猜你喜欢
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
相关资源
最近更新 更多