【问题标题】:C# how to do arithmetic operations on a 2d Array matrixC#如何对二维数组矩阵进行算术运算
【发布时间】:2021-12-27 23:44:34
【问题描述】:

我一直在玩弄这段代码,它打印一个带有负数和正数的小矩阵, 我想要一种有效的方法来仅将矩阵上的正元素相加并获得这些元素的乘积也可以这样做,但在特定数字之后,例如矩阵上的最高值

   static void Main(string[] args)
            {
                int row = 5;
                int column = 5;  
    
                int[,] array = new int[row, column];
                Random rand = new Random();
    
                for (int i = 0; i < row; i++)
                {
                    for (int j = 0; j < column; j++)
                    {
                        array[i, j] = rand.Next(-5, 10);
    
                    }
                }
                for (int i = 0; i < array.GetLength(0); i++)
                {
                    for (int j = 0; j < array.GetLength(1); j++)
                    {
                        Console.Write(array[i, j].ToString() + "  ");
                    }
                    Console.WriteLine(" ");
    
                }
                Console.ReadLine();
}

【问题讨论】:

  • 所以你可以只使用 if 语句来检查数组 [i, j] 元素是否 > 0 & > 特定数字....或者我错过了什么?
  • 是的,那部分需要进一步澄清

标签: c# arrays multidimensional-array


【解决方案1】:

要过滤和添加正矩阵元素,您可以执行以下操作:

static void Main(string[] args)
{
    const int rows = 5;
    const int columns = 5;

    var array = new int[rows, columns];
    var rand = new Random();

    int sum = 0;
    bool numberSeen = false;
    int numberToSee = 1;

    for (int row = 0; row < rows; row++)
    {
        for (int col = 0; col < columns; col++)
        {
            var cell = rand.Next(-5, 10);

            if (!numberSeen && (cell == numberToSee))
            {
                numberSeen = true;
            }

            array[row, col] = cell;

            if (numberSeen && (cell > 0))
            {
                sum += cell;
            }
        }
    }

    Console.WriteLine($"sum = {sum}");

    for (int row = 0; row < rows; row++)
    {
        for (int col = 0; col < columns; col++)
        {
            Console.Write(array[row, col].ToString() + "  ");
        }
        Console.WriteLine(" ");

    }
    Console.ReadLine();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2013-02-27
    • 2020-02-05
    相关资源
    最近更新 更多