使用多维数组的 C++ 矩阵相加程序


2023 年 1 月 20 日, 学习电子教程
1625

这里我们讨论一个使用二维数组将两个矩阵相加的 C++ 程序。

什么是矩阵?

矩阵可以定义为数组的数组或以行和列的表格形式存储数据的多维数组。例如,mat[r][c]

其中,

  • mat 是矩阵名称
  • r 是行数 
  • c 是列数

矩阵的大小或阶数定义为矩阵具有的行数和列数。具有“a”行和“b”列的矩阵称为“a × b”矩阵。

如何添加两个矩阵?

只有当两个矩阵的阶数相同时,才能将它们相加。相加时,只需找到对应项的和,并将此和放在结果矩阵的相应位置。

使用多维数组的 C++ 矩阵相加程序。

这里要求用户输入行数 r 和列数 c。对于此 C++ 程序,r c 的值应小于 10。

使用嵌套 for 循环从用户那里读取元素到第一个数组中,并将其添加到第一个矩阵。类似地,读取第二个矩阵 b [i] [j] 的元素。

访问两个数组中每个对应的元素,并将这些元素相加,然后将其存储到另一个名为 sum [i] [j] 的数组的对应位置。可以使用 for 循环来访问元素。

Sum[i][j] = a[i][j] + b[i][j]。

显示矩阵 sum。

算法

步骤 1: 调用头文件 iostream。

步骤 2: 使用 namespace std.

步骤 3: 打开整数类型的主函数; int main()。

步骤 4:声明整数类型变量 r、c、I、j; 以及数组 a[100][100]、b[100][100]、sum[100][100];

步骤 5: 要求用户输入行数(1 到 100)。

步骤 6:将数字读取到变量 r;

步骤 7:要求用户输入列数(1 到 10);

步骤 8:将数字读取到变量 c;

步骤 9:要求用户输入第一个矩阵的元素。

步骤 10:将元素读取到数组 a[100][100];

步骤 11: 要求用户输入第二个矩阵的元素;

步骤 12:将元素读取到数组 b[100][100];

步骤 13: 获取两个矩阵 a[100][00] b[100][100] 的第一个元素,并将元素相加,然后将它们存储在矩阵 sum[100][100] 的第一个位置。

步骤 14:继续执行步骤 13,直到 a[r][c] b[r][c] ,并将结果存储在 sum[r][c];

步骤 15: 显示 sum[100][100]

步骤 16:退出。

C++ 源代码

                                          #include <iostream>
using namespace std;

int main()
{
    int r, c, a[100][100], b[100][100], sum[100][100], i, j;

    cout << "Enter number of rows (between 1 and 100): ";
    cin >> r;

    cout << "Enter number of columns (between 1 and 100): ";
    cin >> c;

    cout << endl << "Enter elements of 1st matrix: " << endl;

    // Storing elements of first matrix entered by user.
    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element a" << i + 1 << j + 1 << " : ";
           cin >> a[i][j];
       }

    // Storing elements of second matrix entered by user.
    cout << endl << "Enter elements of 2nd matrix: " << endl;
    for(i = 0; i < r; ++i)
       for(j = 0; j < c; ++j)
       {
           cout << "Enter element b" << i + 1 << j + 1 << " : ";
           cin >> b[i][j];
       }

    // Adding Two matrices
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
            sum[i][j] = a[i][j] + b[i][j];

    // Displaying the resultant sum matrix.
    cout << endl << "Sum of two matrix is: " << endl;
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
        {
            cout << sum[i][j] << "  ";
            if(j == c - 1)
                cout << endl;
        }

    return 0;
}
                                      

输出

Enter number of rows (between 1 and 100): 2
Enter number of columns (between 1 and 100): 2
Enter elements of 1st matrix: 
Enter element a11 : 4
Enter element a12 : 5
Enter element a21 : 7
Enter element a22 : 9
Enter elements of 2nd matrix: 
Enter element b11 : 42
Enter element b12 : 8
Enter element b21 : 23
Enter element b22 : 6
Sum of two matrix is: 
46  13  
30  15