如何从C#中的多维表中计算每行整数值的摘要?

如何从C#中的多维表中计算每行整数值的摘要?,c#,C#,我有表4x4,希望得到最后几列中3个整数值的摘要 public class Table { static void Main() { int row, column; int sumrow = 0; int sumcolumn = 0; int[,] numbers = new int[4, 4]; for (row = 0; row <

我有表4x4,希望得到最后几列中3个整数值的摘要

public class Table
{
        static void Main()
        {
            int row, column;
            int sumrow = 0;
            int sumcolumn = 0;

            int[,] numbers = new int[4, 4];

            for (row = 0; row < 3;row++)
            {
                for (column = 0; column < 3 ; column++)
                {

                    Console.Write("Give number to place [" + row + "," + column + "]: ");
                    numbers[row, column] = int.Parse(Console.ReadLine());
                }
            }


            for (row = 0; row < 2; row++) // how to count it?
            {
                for (column = 0; column < 3; column++)
                {
                    sumrow = numbers[ row ,column] + sumrow;
                    numbers[0, 3] = sumrow;   
                }

            }
        }
}
公共类表
{
静态void Main()
{
int行,列;
int sumrow=0;
int-sumcolumn=0;
整数[,]个数=新整数[4,4];
用于(行=0;行<3;行++)
{
对于(列=0;列<3;列++)
{
Console.Write(“给地方编号[“+行+”,“+列+”]:”;
numbers[row,column]=int.Parse(Console.ReadLine());
}
}
for(row=0;row<2;row++)//如何计数?
{
对于(列=0;列<3;列++)
{
sumrow=数字[行,列]+sumrow;
数字[0,3]=sumrow;
}
}
}
}

您可以对二维数组的列求和,如下所示:

IEnumerable<int> columnSums = Enumerable
    .Range(0, numbers.GetLength(0))
    .Select(col => Enumerable
                     .Range(0, numbers.GetLength(1))
                     .Sum(row => numbers[col, row]))
IEnumerable columnSums=可枚举
.Range(0,number.GetLength(0))
.选择(列=>可枚举
.范围(0,数字.GetLength(1))
.Sum(行=>数字[列,行])

未测试,并且可能列和行的循环方式错误…

在请求用户输入后,您拥有一个二维数组,最后一行和列中的所有零,例如:

 1  2  3  0
 4  5  6  0
 7  8  9  0
 0  0  0  0
您希望最后的行和列填充相应行或列的总和:

 1  2  3  6
 4  5  6 15
 7  8  9 24
12 15 18 45
数组中的每个非汇总项贡献三个总计:行总计、列总计和总计(所有元素的总和),如下所示:

 0  0  0  0
 0  X  0  X
 0  0  Y  Y
 0  X  Y  X+Y
作为一种方法,您可以枚举每个数据(非摘要)元素,并相应地更新三个相应的摘要元素:

int rowCount = numbers.GetLength(0) - 1; // # rows, exc. total
int columnCount = numbers.GetLength(1) - 1; // # cols, exc. total
for (row = 0; row < rowCount; row++)
{
    for (column = 0; column < columnCount; column++)
    {
        int cell = numbers[row, column];
        checked // throw on arithmetic overflow
        {
             numbers[row, columnCount] += cell;
             numbers[rowCount, column] += cell;
             numbers[rowCount, columnCount] += cell;   
        }
    }
}
int rowCount=numbers.GetLength(0)-1;/#行,除外总计
int columnCount=numbers.GetLength(1)-1;//#cols,exc.总计
对于(行=0;行<行计数;行++)
{
对于(列=0;列<列计数;列++)
{
int单元格=数字[行,列];
选中//抛出算术溢出
{
数字[行、列计数]+=单元格;
数字[行计数,列]+=单元格;
数字[行计数,列计数]+=单元格;
}
}
}

请注意,这种方法假设最后一行和最后一列最初都是零,这在您的示例中适用。它不要求原始数组是正方形。

问题是什么?@AlexanderDerck:问题是“如何计算整数值的摘要”,但我不明白问题的意思。雷姆斯,你能澄清这个问题吗?嗯。。。我试过了,但最后一列还是得到了0汉克斯,我只得到了所有值的摘要,无法得到如何只计算每行或每列的摘要。。。。