使用多维数组在C++程序中减去两个矩阵


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

在这里我们讨论一个C++程序,用于在二维数组中减去两个矩阵。

什么是矩阵?

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

其中,

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

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

如何减去两个矩阵?

我们只能在两个矩阵的阶数匹配时进行矩阵减法。 要减去两个矩阵,我们必须将矩阵A的正确位置的元素从矩阵B的元素中减去。

如何使用C++程序减去两个矩阵?

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

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

访问“a”和“b”两个数组中的每个相应元素,减去这些元素,并将其存储在另一个名为sub [i] [j]的数组的相应位置。嵌套for循环用于减去表格形式矩阵中的每个元素。

Sub[i][j] = a[i] [j] - B[i][j]。 显示矩阵sub。

算法

步骤 1: 调用头文件 iostream。

第 2 步:使用 namespace std

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

步骤4:声明整数类型变量r、c、I、j;以及数组a[100][100]、b[100][100]、 sub[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] ,并减去这些元素,然后将它们存储在矩阵sub[100][100]的第一个位置。

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

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

步骤16:退出。

C++ 源代码

                                          #include <iostream>
using namespace std;

int main()
{
    int r, c, a[100][100], b[100][100], sub[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)
            sub[i][j] = a[i][j] - b[i][j];

    // Displaying the resultant sum matrix.
    cout << endl << "Subtracted result of two matrix is: " << endl;
    for(i = 0; i < r; ++i)
        for(j = 0; j < c; ++j)
        {
            cout << sub[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 : 6
Enter element a12 : 9
Enter element a21 : 8
Enter element a22 : 4
Enter elements of 2nd matrix: 
Enter element b11 : 8
Enter element b12 : 6
Enter element b21 : 2
Enter element b22 : 4
Subtracted result of two matrix is: 
-2  3  
6  0