c++矩阵乘法
时间: 2023-07-19 13:12:49 浏览: 60
C++中矩阵乘法可以通过使用嵌套循环来实现。假设我们有两个矩阵A和B,它们的尺寸分别为m * n和n * p。那么它们的乘积C的尺寸为m * p。下面是一个示例代码:
```c++
#include <iostream>
using namespace std;
int main()
{
int m, n, p;
cout << "Enter the dimensions of matrices A and B (m, n, p): ";
cin >> m >> n >> p;
// Initialize matrices A and B
int A[m][n], B[n][p];
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 elements of matrix B:" << endl;
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 matrix C
cout << "Result matrix C:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
在这个示例代码中,我们首先从用户输入矩阵的尺寸和元素开始。然后使用嵌套循环初始化矩阵A和B。接着,我们使用嵌套循环计算矩阵C的元素,最后打印出矩阵C。