用C++实现这样一个程序:输入两个矩阵。计算两个矩阵的乘积并输出
时间: 2023-11-06 16:08:25 浏览: 236
以下是用C++实现输入两个矩阵,计算它们的乘积并输出的程序:
```cpp
#include <iostream>
using namespace std;
int main() {
int m, n, p;
cout << "Enter the dimensions of matrix A (m x n): ";
cin >> m >> n;
cout << "Enter the dimensions of matrix B (n x p): ";
cin >> n >> p;
// Initialize matrices A and B
int A[m][n], B[n][p];
cout << "Enter the elements of matrix A:\n";
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
cout << "Enter the elements of matrix B:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
cin >> B[i][j];
}
}
// Multiply matrices A and B
int C[m][p];
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Print the result
cout << "The product of matrices A and B is:\n";
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
在程序中,我们首先输入矩阵 A 和矩阵 B 的维度,然后分别输入矩阵 A 和矩阵 B 的元素。接着,我们使用三重循环计算矩阵 A 和矩阵 B 的乘积,并将结果存储在矩阵 C 中。最后,我们输出矩阵 C 的元素作为乘积的结果。
需要注意的是,这里使用了 C++ 中的多维数组来存储矩阵,并且程序中没有对矩阵的维度进行检查,因此需要确保输入的维度是合法的。
阅读全文
相关推荐



















