#include <iostream>
using namespace std;
#define MAXSIZE 101
typedef struct {
float coef; //系数
int expn; //指数
}Polynomial;
typedef struct {
Polynomial* elem;
int length;
}SqList;
void seletSort(SqList& L) { //选择排序
Polynomial temp;
for (int i = 1; i < L.length; i++) {
for (int j = i + 1; j <= L.length; j++) {
if (L.elem[i].expn < L.elem[j].expn) {
temp = L.elem[j];
L.elem[j] = L.elem[i];
L.elem[i] = temp;
}
}
}
}
void InitList(SqList &L) {
L.elem = new Polynomial[MAXSIZE];
if (!L.elem)exit(1);
L.length = 0;
}
void assignList(SqList& L) { //赋值操作
InitList(L);
int i = 1; //9 2 6 7 6 5 4 3 1 4 5 9 2 1 0 0
//5 6 2 9 -9 3 1 0 5 1 -7 2 -10 4 0 0
cout << "请输入多项式系数和幂次,分别输入两个0结束读入" << endl;
while (1){
cout << "第" << i << "项:";
cin >> L.elem[i].coef;
cin >> L.elem[i].expn;
if (L.elem[i].coef == 0 && L.elem[i].expn == 0)break;
i++;
L.length++;
}
seletSort(L);
cout << "赋值完成" << endl;
}
void print(SqList L) {
for (int i = 1; i <= L.length; i++) { //if判断当系数为0、1,幂次为0、1的特殊情况
if (L.elem[i].coef == 0)continue;//系数为0
if(L.elem[i].expn==0)cout << L.elem[i].coef ;//幂次为0
else if (L.elem[i].expn == 1&& L.elem[i].coef == 1)cout << "X" ;//幂次系数均为1
else if (L.elem[i].expn == 1)cout << L.elem[i].coef << "X" ;//幂次为1
else cout << L.elem[i].coef << "X^" << L.elem[i].expn ;
if (i != L.length&& L.elem[i+1].coef>0)cout << '+'; //后面的系数为负数最后一项没有加号
}
cout << endl;
}
void addPloy(SqList L1,SqList L2,SqList& L3) {
L3.elem = new Polynomial[2 * MAXSIZE];
int i = 1, j = 1,k = 1;
while (i <= L1.length && j <= L2.length) {
if (L1.elem[i].expn > L2.elem[j].expn) {
L3.elem[k] = L1.elem[i];
i++; k++;
}
else if(L1.elem[i].expn < L2.elem[j].expn) {
L3.elem[k] = L2.elem[j];
j++; k++;
}
else { //合并同类项
L3.elem[k].coef = L2.elem[j].coef+ L1.elem[i].coef;
L3.elem[k].expn = L2.elem[j].expn;
i++; j++; k++;
}
}
if (i > L1.length) {
while (j <= L2.length) {
L3.elem[k] = L2.elem[j];
j++; k++;
}
}
else {
while (i <= L1.length) {
L3.elem[k] = L1.elem[i];
i++; k++;
}
}
L3.length=k-1;
}
void transformInverse(SqList& L) { //各项系数转换为相反数
for (int i = 1; i <= L.length; i++) {
L.elem[i].coef = -L.elem[i].coef;
}
}
void minusPloy(SqList L1, SqList& L2, SqList& L3) {
transformInverse(L2);//被减式子系数全部转为相反数再相加
addPloy(L1, L2, L3);
}
int main() {
SqList P1,P2,P3;
int n;
cout << "输入1两式相加,输入2两式相减"<<endl;
cin >> n;
switch (n)
{
case 1:
cout << "输入第一个式:" << endl;
assignList(P1);
print(P1);
cout << "输入第二个式:" << endl;
assignList(P2);
print(P2);
cout << "完成相加操作:" << endl;
addPloy(P1, P2, P3);
print(P3);
break;
case 2:
cout << "输入减式:" << endl;
assignList(P1);
print(P1);
cout << "输入被减式:" << endl;
assignList(P2);
print(P2);
cout << "完成相减操作:" << endl;
minusPloy(P1, P2, P3);
print(P3);
break;
default:
cout << "非法输入" << endl;
break;
}
return 0;
}
C++:顺序表完成两个一元多项式加减法
最新推荐文章于 2023-04-16 02:32:32 发布