题解 | #计算两个矩阵的乘积#
计算两个矩阵的乘积
https://www.nowcoder.com/practice/ed6552d03e624ba58d16af6d57e1c3e9
#include <iostream> #include<cstdio> using namespace std; struct Matrix { int matrix[3][3]; int row, col; Matrix(int r, int c): row(r), col(c) {} }; void printMatrix(Matrix x) { for (int i = 0; i < x.row; i++) { for (int j = 0; j < x.col; j++) { cout << x.matrix[i][j] << " "; } printf("\n"); } } Matrix multiMatrix(Matrix x, Matrix y) { Matrix res(x.row, y.col); for (int i = 0; i < x.row; i++) { for (int j = 0; j < y.col; j++) { res.matrix[i][j] = 0; for (int k = 0; k < x.col; k++) { res.matrix[i][j] += (x.matrix[i][k] * y.matrix[k][j]); // cout<<res.row; // cout<<res.matrix[i][j]<<"\n"; } } } return res;//别忘了return,没提示,表现在返回res后发现res.row为0 } int main() { Matrix x(2, 3), y(3, 2); for (int i = 0; i < x.row; i++) { for (int j = 0; j < x.col; j++) { scanf("%d", &x.matrix[i][j]); } } for (int i = 0; i < y.row; i++) { for (int j = 0; j < y.col; j++) { scanf("%d", &y.matrix[i][j]); } } Matrix res = multiMatrix(x, y); // cout<<res.row; printMatrix(res); return 0; }