Skip to main content
 首页 » 编程设计

C# 添加两个二维数组

2024年02月13日13artech

好的,正如标题所说,我需要帮助找到一种将两个数组相加的简单方法。 到目前为止,这是我的代码:

static void Main() 
{ 
    Console.Write("Enter Rows: "); 
    int row = Convert.ToInt32(Console.ReadLine()); 
    Console.Write("Enter Columns: "); 
    int col = Convert.ToInt32(Console.ReadLine()); 
    int[,] a = new int[row, col]; 
    for (int i = 0; i < row; i++) 
    { 
        for (int j = 0; j < col; j++) 
        { 
            Console.Write("Enter Matrix({0},{1}): ", i, j); 
            a[i, j] = Convert.ToInt32(Console.ReadLine()); 
        } 
    } 
    int[,] b = new int[row, col]; 
    for (int i = 0; i < row; i++) 
    { 
        for (int j = 0; j < col; j++) 
        { 
            Console.Write("Enter Matrix({0},{1}): ", i, j); 
            a[i, j] = Convert.ToInt32(Console.ReadLine()); 
        } 
    } 

那么,我如何将这两个数组加在一起,并打印出结果。 谢谢。

请您参考如下方法:

static void Main() 
{ 
    // Your code 
 
    int[,] result = new int[row, col]; 
 
    for (int i = 0; i < row; i++) 
    { 
        for (int j = 0; j < col; j++) 
        { 
            result [i, j] = a[i,j] + b[i,j]; 
 
            Console.Write(result[i, j] + " "); 
        } 
 
        Console.WriteLine(); 
    } 
}