- 积分
- 4
- 注册时间
- 2002-10-1
- 仿真币
-
- 最后登录
- 1970-1-1
|
#include <stdio.h>
const minsize=5;
struct element
{
short row,col;
double val;
element *next;
};
class matrix
{
short rows,cols;
element * elems;
double dummy;
double & insertelem(element * elem,short row,short col);
public:
matrix(short rows,short cols);
~matrix();
short rows1(){return rows;}
short cols1(){return cols;}
double & operator () (short row,short col);
friend matrix operator + (matrix &,matrix &);
friend matrix operator * (matrix &,matrix &);
void print();
};
matrix::matrix(short rows,short cols)
{
matrix::rows =(rows<minsize?minsize:rows);
matrix::cols =(cols<minsize?minsize:cols);
elems=0;
dummy=0.0;
}
matrix::~matrix ()
{
element * elem=elems;
element * tmp;
while(elem!=0)
{
tmp=elem;
elem=elem->next ;
delete tmp;
}
}
double & matrix::insertelem (element *elem,short row,short col)
{
element * newelem=new element;
if (newelem==0)
return dummy;
newelem->row =row;
newelem->col =col;
newelem->val =0.0;
if(elem==elems && (elems==0 || row<elems->row || row==elems->row && col<elems->col ))
{
newelem->next =elems;
elems=newelem;
}
else
{
newelem->next =elem->next;
elem->next =newelem;
}
return newelem->val ;
}
double & matrix:perator () (short row,short col)
{
if (row<1 || row>rows || col<1 || col>cols)
return dummy;
if (elems==0 || row<elems->row || row==elems->row && col<elems->col )
return insertelem(elems,row,col);
for (element * elem=elems;elem->next !=0;elem=elem->next )
{
if (row==elem->next->row )
{
if (col==elem->next ->col )
return elem->next->val;
else if (col<elem->next ->col )
break;
}
else if (row<elem->next ->row )break;
}
return insertelem(elem,row,col);
}
matrix operator + (matrix & p,matrix & q)
{
matrix m(p.rows ,q.cols );
for (element * pe=p.elems ;pe!=0;pe=pe->next )
m(pe->row ,pe->col )=pe->val ;
for (element * qe=q.elems ;qe!=0;qe=qe->next )
m(qe->row ,qe->col )+=qe->val ;
return m;
}
matrix operator * (matrix & p,matrix & q)
{
matrix m(p.rows ,q.cols );
for (element * pe=p.elems ;pe!=0;pe=pe->next )
for (element * qe=q.elems ;qe!=0;qe=qe->next )
if (pe->col ==qe->row )
m(pe->row ,qe->col )+=pe->val *qe->val ;
return m;
}
void matrix::print ()
{
element * elem =elems;
for (short row =1;row<=rows;++row)
{
for (short col =1;col<=cols;++col)
if(elem!=0 && elem->row==row && elem->col==col)
{
printf("%8.2f",elem->val);
elem=elem->next;
}
else printf("%8.2f",0.0);
printf("\n");
}
printf("\n");
}
int main()
{
matrix ma1(5,5);
matrix ma2(5,5);
matrix ma3(5,5);
ma1(2,2)=1.0;
ma1(3,3)=2.0;
ma1(4,4)=3.0;
ma1(1,1)=4.0;
ma1(1,5)=5.0;
ma1(1,3)=6.0;
ma2(2,2)=10.0;
ma2(3,3)=20.0;
ma2(3,5)=30.0;
ma2(5,2)=40.0;
ma1.print ();
// getchar();
ma2.print ();
// printf("%8.2f\n",ma1(2,2));
ma3=ma1+ma2;
// getchar();
ma3.print ();
ma3=ma1*ma2;
// getchar();
ma3.print ();
return 0;
}
运行时,错误见附件。 |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?注册
×
|