编写一个程序实现矩阵的基本运算(加、减、乘法运算)。(矩阵的维数22)
#include <iostream>
using namespace std;
class pre
{
public:
pre();
void set_a();
void set_b();
void display();
friend pre operator+(pre a,pre b);
friend pre operator*(pre a,pre b);
friend pre operator-(pre a,pre b);
private:
int pr[11][11];
};
pre::pre()
{
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
{
pr[i][j]=0;
}
}
void pre::set_a()
{
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
{
cin>>pr[i][j];
}
}
void pre::set_b()
{
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
{
cin>>pr[i][j];
}
}
void pre::display()
{
for(int i=0; i<2; i++)
{
for(int j=0; j<2; j++)
{
cout<<pr[i][j]<<" ";
if(j==1)
cout<<endl;
}
}
cout<<endl;
}
pre operator+(pre a,pre b)
{
pre c;
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
{
c.pr[i][j]=a.pr[i][j]+b.pr[i][j];
}
return c;
}
pre operator*(pre a,pre b)
{
pre c;
for(int k=0; k<2; k++)
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
{
c.pr[k][j]+=a.pr[k][i]*b.pr[i][j];
}
return c;
}
pre operator-(pre a,pre b)
{
pre c;
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
{
c.pr[i][j]=a.pr[i][j]-b.pr[i][j];
}
return c;
}
int main()
{
pre a,b,c;
cout<<"输入a的 2x2 矩阵:"<<endl;
a.set_a();
cout<<"输入b的 2x2 矩阵:"<<endl;
b.set_b();
cout<<"a的矩阵:"<<endl;
a.display();
cout<<"b的矩阵:"<<endl;
b.display();
c=a+b;
cout<<"a+c矩阵结果为: "<<endl;
c.display();
c=a-b;
cout<<"a-c矩阵结果为: "<<endl;
c.display();
c=a*b;
cout<<"a*c矩阵结果为: "<<endl;
c.display();
return 0;
}
结果: