请写一段c++系统程序,要求进行矩阵乘法 在主函数中输入m和n(0<m,n<=5),分别定义矩 阵,Am×n, Bn×m和Cm×m, 从键盘读入矩阵A和 B中元素的值。调用函数multiply()计算矩阵 C=AXB。并在主函数中输出矩阵C。
时间: 2024-05-04 16:21:10 浏览: 256
下面是符合要求的C++程序:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 5;
void multiply(int A[][MAX_SIZE], int B[][MAX_SIZE], int C[][MAX_SIZE], int m, int n)
{
for (int i = 0; i < m; ++i) {
for (int j = 0; j < m; ++j) {
C[i][j] = 0;
for (int k = 0; k < n; ++k) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
int main()
{
int m, n;
int A[MAX_SIZE][MAX_SIZE], B[MAX_SIZE][MAX_SIZE], C[MAX_SIZE][MAX_SIZE];
// 输入矩阵A和B的元素
cout << "Enter the number of rows and columns for matrix A (m n): ";
cin >> m >> n;
cout << "Enter the elements of matrix A:" << endl;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
cin >> A[i][j];
}
}
cout << "Enter the number of rows and columns for matrix B (n m): ";
cin >> n >> m;
cout << "Enter the elements of matrix B:" << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> B[i][j];
}
}
// 计算矩阵C
multiply(A, B, C, m, n);
// 输出矩阵C
cout << "The result of matrix multiplication is:" << endl;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < m; ++j) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
程序中,`multiply()`函数实现了矩阵乘法的计算,它接收三个参数:矩阵A、B和C的数组指针,以及矩阵A和B的行数和列数。在`main()`函数中,先读入矩阵A和B的元素值,然后调用`multiply()`函数计算矩阵C,最后输出矩阵C的元素值。注意,程序中使用了常量`MAX_SIZE`来限制矩阵的最大尺寸,以确保程序的安全性。
阅读全文
相关推荐

















