简介
使用结构体的一维数组进行对称矩阵的相加与相乘的操作。
结构体代码
struct TSMatrix
{
int rows;
int cols;
int data;
bool b;
};
矩阵输入代码
void CreateMat(TSMatrix *t,int n) //存入矩阵值
{
int i,num = 0;
for(i = 0 ; i < n ; i++)
{
for(int j = 0 ; j <= i ; j++)
{
int data;
cout<<"请输入对称矩阵中下三角的第 "<<i+1<<" 行"<<" 第 "<<j+1<<" 列元素的值:"<<endl;
t[num].rows = i;
t[num].cols = j;
cin>>data;
t[num].data = data;
t[num].b = true;
num += 1;
}
}
}
矩阵输出代码
void DispMat(TSMatrix t[],int n) //矩阵输出
{
if(t[0].b == false )
{
cout<<"无矩阵"<<endl;
return ;
}
for(int r = 0 ; r < n ; r++)
{
for(int c = 0 ; c < n ; c++)
{
int num = 0;
while(1)
{
if((t[num].rows == r && t[num].cols == c) || (t[num].cols == r && t[num].rows == c))
{
cout<<t[num].data<<"\t";
break;
}
num += 1;
}
}
cout<<endl;
}
}
矩阵相加的代码
void add(TSMatrix t1[],TSMatrix t2[],TSMatrix t3[],int n)
{
t3[0].b = true;
for(int i = 0 ; i < (n * (n+1) / 2) ; i++)
{
t3[i].data = (t1[i].data + t2[i].data);
t3[i].rows = t1[i].rows;
t3[i].cols = t1[i].cols;
}
}
相乘的代码:
不知道为什么不能复制代码进来,就粘贴复制图片吧。
主函数:
int main()
{
int n;
cout<<"请输入两个对称矩阵的阶数:"<<endl;
cin>>n;
cout<<"请输入第一个对称矩阵:"<<endl;
TSMatrix *t1 = new TSMatrix[n * (n+1) / 2];
CreateMat(t1,n);
cout<<"请输入第二个对称矩阵:"<<endl;
TSMatrix *t2 = new TSMatrix[n * (n+1) / 2];
CreateMat(t2,n);
cout<<"矩阵1:"<<endl;
DispMat(t1,n);
cout<<"矩阵2:"<<endl;
DispMat(t2,n);
TSMatrix *t3 = new TSMatrix[n * (n+1) / 2];
cout<<"矩阵相加:"<<endl;
add(t1,t2,t3,n);
DispMat(t3,n);
TSMatrix *t4 = new TSMatrix[n * (n+1) / 2];
cout<<"矩阵相乘:"<<endl;
tul(t1,t2,t4,n);
cout<<endl;
DispMat(t4,n);
}