c语言数据结构实现无序一元多项式的加法运算,以(0,0)作为输入结束
时间: 2023-05-30 09:06:00 浏览: 36
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
// 定义一元多项式结构体
typedef struct {
float coef; // 系数
int expn; // 指数
} ElemType;
typedef struct {
ElemType *elem; // 存储空间基地址
int length; // 当前长度
int listsize; // 分配的存储容量
} SqList;
// 初始化线性表
void InitList(SqList *L) {
L->elem = (ElemType *)malloc(MAXSIZE * sizeof(ElemType));
if (!L->elem) {
exit(0); // 存储分配失败
}
L->length = 0;
L->listsize = MAXSIZE;
}
// 增加线性表长度
void IncreaseSize(SqList *L, int len) {
ElemType *newbase;
newbase = (ElemType *)realloc(L->elem, (L->listsize + len) * sizeof(ElemType));
if (!newbase) {
exit(0); // 存储分配失败
}
L->elem = newbase;
L->listsize += len;
}
// 插入元素
void ListInsert(SqList *L, int i, ElemType e) {
if (i < 1 || i > L->length + 1) { // i值不合法
exit(0);
}
if (L->length >= L->listsize) { // 当前存储空间已满,增加分配
IncreaseSize(L, MAXSIZE);
}
ElemType *q = &(L->elem[i - 1]);
for (ElemType *p = &(L->elem[L->length - 1]); p >= q; --p) {
*(p + 1) = *p;
}
*q = e;
++L->length;
}
// 一元多项式相加
void AddPolyn(SqList *La, SqList *Lb) {
int i = 1, j = 1, k = 0;
while (i <= La->length && j <= Lb->length) {
if (La->elem[i - 1].expn == Lb->elem[j - 1].expn) { // 指数相等,系数相加
float sum = La->elem[i - 1].coef + Lb->elem[j - 1].coef;
if (sum != 0) {
ElemType e = {sum, La->elem[i - 1].expn};
ListInsert(La, ++k, e);
}
++i;
++j;
} else if (La->elem[i - 1].expn < Lb->elem[j - 1].expn) { // 将La中指数较小的赋值给结果多项式
ListInsert(La, ++k, La->elem[i - 1]);
++i;
} else { // 将Lb中指数较小的赋值给结果多项式
ListInsert(La, ++k, Lb->elem[j - 1]);
++j;
}
}
// 将La或Lb中剩余的元素添加到结果多项式中
while (i <= La->length) {
ListInsert(La, ++k, La->elem[i - 1]);
++i;
}
while (j <= Lb->length) {
ListInsert(La, ++k, Lb->elem[j - 1]);
++j;
}
}
int main() {
SqList La, Lb;
InitList(&La);
InitList(&Lb);
printf("请输入多项式1的系数和指数,以(0,0)作为输入结束:\n");
float coef;
int expn;
scanf("%f,%d", &coef, &expn);
while (coef != 0 || expn != 0) {
ElemType e = {coef, expn};
ListInsert(&La, La.length + 1, e);
scanf("%f,%d", &coef, &expn);
}
printf("请输入多项式2的系数和指数,以(0,0)作为输入结束:\n");
scanf("%f,%d", &coef, &expn);
while (coef != 0 || expn != 0) {
ElemType e = {coef, expn};
ListInsert(&Lb, Lb.length + 1, e);
scanf("%f,%d", &coef, &expn);
}
AddPolyn(&La, &Lb);
printf("多项式相加的结果为:\n");
for (int i = 0; i < La.length; ++i) {
printf("%.1fX^%d", La.elem[i].coef, La.elem[i].expn);
if (i != La.length - 1) {
printf("+");
}
}
printf("\n");
return 0;
}
相关推荐
















