用c++实现一个函数multi,其可以实现两个任意大小的矩阵相乘,通过主函数调用该函数,并输出结果
时间: 2024-05-01 12:23:34 浏览: 21
以下是一个可能的实现,其中使用了C++的标准库vector来表示矩阵:
```c++
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> multi(vector<vector<int>> A, vector<vector<int>> B) {
int m = A.size();
int n = B[0].size();
int k = B.size();
vector<vector<int>> C(m, vector<int>(n));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
for (int l = 0; l < k; l++) {
C[i][j] += A[i][l] * B[l][j];
}
}
}
return C;
}
int main() {
vector<vector<int>> A = {{1, 2}, {3, 4}};
vector<vector<int>> B = {{5, 6}, {7, 8}};
vector<vector<int>> C = multi(A, B);
for (int i = 0; i < C.size(); i++) {
for (int j = 0; j < C[0].size(); j++) {
cout << C[i][j] << ' ';
}
cout << endl;
}
return 0;
}
```
该程序输入两个矩阵A和B,使用multi函数计算它们的乘积,并输出结果矩阵C。在multi函数中,首先计算出C的大小,然后使用三重循环计算C的每个元素。在主函数中,使用两层循环输出矩阵C的每个元素。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)