【问题标题】:How to read a matrix from the console and print the sum of all matrix elements如何从控制台读取矩阵并打印所有矩阵元素的总和
【发布时间】:2019-10-07 02:23:03
【问题描述】:

我正在学习 C#,现在我在学习多维数组。我想编写一个程序,从控制台读取矩阵并打印:

  • 行数
  • 列数
  • 所有矩阵元素的总和

因此,在接下来的 [rows] 行中,我将获取用逗号和空格分隔的每一列的元素。我为总和做了一个foreach,但我不明白如何将元素插入矩阵。如果您能帮助我,我将不胜感激!

int[] dimensions = Console.ReadLine()
.Split(", ", StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToArray(); 

int rows = dimensions[0];
int columns = dimensions[1];

int[,] matrix = new int[rows,columns];

for (int i = 0; i < rows; i++)
{ 
    int[] numbers = Console.ReadLine()
        .Split(", ", StringSplitOptions.RemoveEmptyEntries)
        .Select(int.Parse)
        .ToArray();
//I do not know how to add the elements here
}

int sum = 0;
foreach (var element in matrix)
{
    sum += element;
}

【问题讨论】:

    标签: c# matrix multidimensional-array


    【解决方案1】:

    您可以使用 Linq Sum() 计算所有行的总和

    当您已经遍历输入数据的每一行时,您可以分配一个名为sum =0 的临时变量,并为每一行计算该行所有数字的总和并将其添加到临时变量,即sum。

    int sum = 0;
    for (int i = 0; i < rows; i++)
    { 
        int[] numbers = Console.ReadLine()
            .Split(", ", StringSplitOptions.RemoveEmptyEntries)
            .Select(int.Parse)
            .ToArray();
        sum += numbers.Sum(); //Calculate sum of all numbers in a row and add it to existing sum variable.
    //I do not know how to add the elements here
    }
    
    Console.WriteLine("Sum of all numbers" + sum); //print sum of all numbers i.e. 76
    

    【讨论】:

    • @NikolDimitrova,请检查我的答案,计算总和的优雅方法
    • 感谢您的回复!正如我所说,我想将元素插入矩阵并然后计算总和。
    【解决方案2】:

    使用两个索引访问二维数组中的元素:

    for (int i = 0; i < rows; i++)
    { 
        int[] numbers = Console.ReadLine()
            .Split(", ", StringSplitOptions.RemoveEmptyEntries)
            .Select(int.Parse)
            .ToArray();
    
        for (int j = 0; j < columns; j++)
        {
            matrix[i,j]=numbers[j];
        }
    }
    
    int sum = 0;
    for (int i = 0; i < rows; i++)
    { 
        for (int j = 0; j < columns; j++)
        {
            sum += matrix[i,j];
        }
    }
    

    【讨论】:

    • 感谢您的回复,但我正在寻找多维数组的解决方案,因为这是我目前正在学习的内容。
    • @NikolDimitrova ,好的,我已经用二维数组更新了我的答案
    • @Renat, @nikolDimitrova 无需使用二维数组,只需 Linq sum() 函数即可为您工作...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2016-11-13
    • 1970-01-01
    • 2015-03-15
    相关资源
    最近更新 更多