#include <iostream>
using namespace std;
class SymMatrix
{
private:
int order;//阶数
int *data;//存放下三角的一维数组
public:
SymMatrix(int n)//初始化矩阵阶数
{
order = n;
data= new int[(order + 1) * order / 2];
//int num = order * (order + 1) / 2;
//data = new int[num];
}
void Creat()//输入元素值
{
for (int i = 1; i <= order; i++)
{
cout << "请输入第" << i << "行元素:" << endl;
for (int j = 1; j <= i; j++)
{
int index = i * (i - 1) / 2 + j - 1;
cin >> data[index];
}
}
}
int Get(int i, int j)//查询i行j列元素值
{
if (i > order || j>order ||i<1 || j < 1)
{
cout << "查询的位置错误" << endl;
}
if (i < j)
{
return *(data + j * (j - 1) / 2 + i - 1);
}
else
{
return *(data + i * (i - 1) / 2 + i - 1);
}
}
void Print()//输出矩阵
{
for (int i = 1; i <=order; i++)
{
for (int j = 1; j <=order; j++)
{
if (i < j)
{
cout << *(data + j * (j - 1) / 2 + i - 1)<<" ";
}
else
cout << *(data + i * (i - 1) / 2 + j - 1) << " ";
}
cout << endl;
}
}
SymMatrix Add(SymMatrix B)//对称矩阵的加法
{
if (order != B.order)
{
cout << "阶数不同,不能相加!" << endl;
system("pause");
exit(1);
}
else
for (int i = 0; i < order; i++)
{
for (int j = 0; j < order; j++)
{
if (i > j)
{
cout << data[((i + 1) * i) / 2 + j] + B.data[((i + 1) * i) / 2 + j] << " ";
}
else
cout << data[((j + 1) * j) / 2 + i] + B.data[((j + 1) * j) / 2 + i] << " ";
}
cout << endl;
}
}
};
int main()
{
int x;
cout << "输入矩阵M的阶数:" << endl;
cin >> x;
SymMatrix M(x);
cout << "输入矩阵M的各个元素:" << endl;
M.Creat();
M.Print();
cout << "输入要查询元素的位置:" << endl;
int i, j;
cout << "行号:"; cin >> i;
cout << "列号:";cin>> j;
cout<<M.Get(i, j)<<endl;
int y;
cout << "输入第二个矩阵的阶数:" << endl;
cin >> y;
SymMatrix B(y);
B.Creat();
B.Print();
cout << endl;
B.Add(M);
}