介绍
在本实验中,我们将编写一个 C++ 程序,使用二维数组(2D arrays)来实现两个矩阵的相加。
在本实验中,我们将编写一个 C++ 程序,使用二维数组(2D arrays)来实现两个矩阵的相加。
在 ~/project 目录下创建一个名为 add_matrices.cpp 的 C++ 文件。这将是我们编写代码的主文件。
cd ~/project
touch add_matrices.cpp
将以下代码复制并粘贴到 add_matrices.cpp 文件中。
#include <iostream>
using namespace std;
int main() {
cout << "\n\nWelcome to the Add Matrices Program\n\n\n";
// 初始化变量
int row, col, i, j;
// 声明三个矩阵(二维数组)
int m1[10][10], m2[10][10], sum[10][10];
// 从用户获取矩阵的行数和列数
cout << "\nEnter the number of Rows and Columns of matrix : ";
cin >> row >> col;
// 从用户获取第一个矩阵的元素
cout << "\nEnter the " << row * col << " elements of first matrix : \n";
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cin >> m1[i][j];
}
}
// 从用户获取第二个矩阵的元素
cout << "\nEnter the " << row * col << " elements of second matrix : \n";
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cin >> m2[i][j];
}
}
// 计算和矩阵
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
sum[i][j] = m1[i][j] + m2[i][j];
}
}
// 显示矩阵
cout << "\n\nThe first matrix is : \n";
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cout << m1[i][j] << " ";
}
cout << endl;
}
cout << "\n\nThe second matrix is : \n";
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cout << m2[i][j] << " ";
}
cout << endl;
}
cout << "\n\nThe Sum matrix is : \n";
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
cout << sum[i][j] << " ";
}
cout << endl;
}
return 0;
}
要编译代码,请在 ~/project 目录下打开终端,并运行以下命令:
g++ add_matrices.cpp -o add_matrices
要运行程序,请在终端中输入以下命令:
./add_matrices
这将运行程序并输出两个矩阵相加的结果。
运行程序后,你应该会看到如下输出:
Welcome to the Add Matrices Program
Enter the number of Rows and Columns of matrix : 2 2
Enter the 4 elements of first matrix :
1 2 3 4
Enter the 4 elements of second matrix :
5 6 7 8
The first matrix is :
1 2
3 4
The second matrix is :
5 6
7 8
The Sum matrix is :
6 8
10 12
在本实验中,我们学习了如何使用 C++ 编程语言中的二维数组(2D arrays)来实现两个矩阵的相加。我们创建了一个程序,该程序接收两个矩阵作为输入,将两个矩阵的对应元素相加,并输出和矩阵。