这是我的多维数组。
1-2-3-4
5-6-7-8
9-10-11-12
13-14-15-16
我想找到反向对角线元素的总和(从:右上到:左下)(4 -> 7 -> 10 -> 13)
这是我的代码,它给出了一个错误,但我仍然找不到原因。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace sketchboard
{
class Program
{
static int reversediagonaladder (int[,] a)
{
int sum = 0;
for(int row=a.GetLength(0) ; row>0 ; row--)
{
for(int column=a.GetLength(1) ; column>0 ; column--)
{
if (row == column)
sum += a[row , column];
}
}
Console.WriteLine($"{sum}");
return sum;
}
static void Main(string[] args)
{
int[,] a ={ {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16 } };
reversediagonaladder(a);
Console.ReadLine(); // added for hold console on screen
}
}
}
答案 0 :(得分:1)
您的循环以 a.GetLength(1)
或 a.GetLength(0)
开头,在这两种情况下,这将解析为 4
但没有索引 4
,因为索引以 0
开头.
所以索引将是 0, 1, 2 or 3
,它等于 4
的长度。
要解决您的问题,您需要从长度中减去 1
。
目前你也在跳过索引 0
,我不知道你为什么这样做,也许这也是一个错误,要解决这个问题,你必须改变 {{1} 的中断条件} 从 for
循环到 > 0
。
这应该有效
>= 0
编辑:
这里有一个版本,它实际上完成了问题所声称的功能,它还摆脱了应该运行更高性能的双 for 循环
for (int row = a.GetLength(0) - 1; row >= 0; row--)
{
for (int column = a.GetLength(1) - 1; column >= 0; column--)
{
if (row == column)
sum += a[row , column];
}
}
在这里你可以看到它的实际效果:
答案 1 :(得分:1)
如果您不想处理 -1
,请改用 GetUpperBound。
这是一个按照 Self 建议执行的示例,仅使用一个 for
循环:
public static void Main(string[] args)
{
int[,] a ={ {1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16} };
int sum = reversediagonaladder(a);
Console.WriteLine("sum = " + sum);
Console.WriteLine();
Console.WriteLine("Press Enter to Quit");
Console.ReadLine();
}
static int reversediagonaladder(int[,] a)
{
// code assumes a SQUARE matrix
int sum = 0;
for (int row=0, col=a.GetUpperBound(1); row<=a.GetUpperBound(0) && col>=0; row++, col--)
{
sum += a[row, col];
}
return sum;
}