编程实现矩阵相加和相减 c++
编程实现矩阵相加和相减。(提示:定义矩阵类,数据成员为数组,重载+,-两个运算符)
简单点就ok了。。。。。。。。。
[解决办法]
原来是同学,看这吧<常用算法程序集(C++语言描述)>
[解决办法]
#include<iostream>
using namespace std;
class matrix
{
public:
matrix();
void setMatrix();
friend matrix operator + (matrix a,matrix b);
friend matrix operator - (matrix a,matrix b);
void print();
private:
int data[3][3];
};
void matrix::print ()
{
cout<<"output the matrix:"<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
cout<<data[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}
matrix operator + (matrix a,matrix b)
{
matrix c;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
c.data [i][j]=a.data [i][j]+b.data [i][j];
return c;
}
matrix operator -(matrix a,matrix b)
{
matrix c;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
c.data [i][j]=a.data [i][j]-b.data [i][j];
return c;
}
matrix::matrix()
{
data[0][0]=0;data[0][1]=0;data[0][2]=0;
data[1][0]=0;data[1][1]=0;data[1][2]=0;
data[2][0]=0;data[2][1]=0;data[2][2]=0;
}
void matrix::setMatrix()
{
cout<<"Input 9 numbers:"<<endl;
cin>>data[0][0]>>data[0][1]>>data[0][2];
cin>>data[1][0]>>data[1][1]>>data[1][2];
cin>>data[2][0]>>data[2][1]>>data[2][2];
cout<<" The end!"<<endl;
}
int main()
{
matrix a,b,c;
a.setMatrix();
b.setMatrix();
a.print();
b.print ();
c=a+b;
c.print();
return 0;
}