C++实现矩阵相乘和相加运算 这里只实现了N * N矩阵的相加和相乘,如果想要实现N*M 和 M*S矩阵相乘,得到N*S矩阵,只需要将乘法的i,j改成N和S的值,k对应的是M的值
#include <iostream>
#define N 3
using namespace std;
void Print(int Mx[N][N]){
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
cout<<Mx[i][j]<<" ";
}
cout<<endl;
}
}
void MatrixMultiply(int Mx1[N][N],int Mx2[N][N]){
int Mx[N][N];
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
int sum = 0;
for(int k = 0; k < N; k++){
sum+=Mx1[i][k]*Mx2[k][j];
}
Mx[i][j] = sum;
}
}
cout<<"矩阵相乘结果:\n";
Print(Mx);
}
void MatrixAdd(int Mx1[N][N],int Mx2[N][N]){
int Mx[N][N];
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
Mx[i][j] = Mx1[i][j] + Mx2[i][j];
}
}
cout<<"\n矩阵相加结果:\n";
Print(Mx);
}
int main() {
int Mx1[N][N]={{1,1,1},{1,1,1},{1,1,1}};
int Mx2[N][N]={{1,2,3},{4,5,6},{7,8,9}};
MatrixMultiply(Mx1,Mx2);
MatrixAdd(Mx1,Mx2);
return 0;
}
考研打卡!
|