|
以下是引用heliujin在2006-5-6 8:46:00的发言:
有点错误 希望大家帮我找一找 我们正在学这个呢 谢谢大家了 如果有逻辑错误的话 请不要笑话我:
#include<iostream.h>
#include<iomanip.h>
class matrix
{
short rows,cols;
double *elems;
public:
matrix(){}
matrix(short r,short c);
double operator()(short r,short c);
void setelem(short r,short c,double v);
friend matrix operator+(matrix p,matrix q);
friend matrix operator-(matrix p,matrix q);
friend matrix operator*(matrix p,matrix q);
void print();
};
matrix::matrix(short r,short c)
{
rows=r;
cols=c;
elems=new double[r*c];
}
double matrix::operator ()(short r,short c)
{
return (r>=1&&r<=rows&&c>=1&&c<=cols)?elems[(r-1)*cols+(c-1)]:0.0;
}
void matrix::setelem(short r,short c,double v)
{
if(r>=1&&r<=rows&&c>=1&&c<=cols)
elems[(r-1)*cols+(c-1)]=v;
}
matrix operator+(matrix p,matrix q)
{
matrix m(p.rows,p.cols);
if(p.rows!=q.rows||p.cols!=q.cols)
{
cout<<"error";
}
for(int i=1;i<=p.rows;i++)
{
for(int j=1;j<=p.cols;j++)
{
m.setelem(i,j,p(i,j)+q(i,j));
}
}
return m;
}
matrix operator-(matrix p,matrix q)
{
matrix m(p.rows,p.cols);
if(p.rows!=q.rows||p.cols!=q.cols)
{
cout<<"error";
}
for(int i=1;i<=p.rows;i++)
{
for(int j=1;j<=p.cols;j++)
{
m.setelem(i,j,p(i,j)-q(i,j));
}
}
return m;
}
matrix operator*(matrix p,matrix q)
{
matrix m(p.rows,q.cols);
if(p.cols!=q.rows)
cout<<"error";
for(int i=1;i<=p.rows;i++)
{
for(int j=1;j<=q.cols;j++)
{
m.setelem(i,j,0.0);
for(int k=1;k<=p.cols;k++)
{
m.setelem(i,j,m(i,j)+p(i,k)+q(k,j));
}
return m;
}
} //掉了两个括号,其他没错
}
void matrix::print()
{
for(int i=1;i<=rows;i++)
{
for(int j=1;j<=cols;j++)
{
cout<<setw(7)<<(*this)(i,j);
}
cout<<endl;
}
}
void main()
{
matrix a(2,3),b(2,3),c(3,2),d(2,3),e(2,2);
a.setelem(1,1,-1.1);
a.setelem(1,2,2.2);
a.setelem(1,3,-3.3);
a.setelem(2,1,4.4);
a.setelem(2,2,-5.5);
a.setelem(2,3,6.6);
cout<<"A:"<<endl;a.print();
} |
|