题解 | #计算两个矩阵的乘积#
计算两个矩阵的乘积
http://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){} //构造函数 }; Matrix Multiply(Matrix x,Matrix y) //矩阵乘法 { Matrix answer(x.row,y.col); for(int i=0;i<answer.row;++i){ for(int j=0;j<answer.col;++j){ answer.matrix[i][j]=0; for (int k=0;k<x.col;++k){ answer.matrix[i][j]+=x.matrix[i][k]*y.matrix[k][j]; } } } return answer; } void PrintMatrix(Matrix x){ //输出矩阵 for(int i=0;i<x.row;++i){ for(int j=0;j<x.col;++j){ printf("%d ", x.matrix[i][j]); } printf("\n"); } return; } int main() { Matrix x(2,3); Matrix 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 answer = Multiply(x,y); PrintMatrix(answer); return 0; }