c语言代码实现 一元稀疏多项式计算器
时间: 2023-12-08 10:06:44 浏览: 180
C语言-一元稀疏多项式计算器
以下是C语言代码实现一元稀疏多项式计算器的步骤:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
float coef; // 系数
int expn; // 指数
} ElemType;
typedef struct {
ElemType data[MAXSIZE + 1]; // 存储数组,data[0]存储项数
int length; // 当前项数
} Poly;
void CreatePoly(Poly *P, int m) {
int i;
printf("请输入%d个非零项的系数和指数:\n", m);
for (i = 1; i <= m; i++) {
scanf("%f%d", &P->data[i].coef, &P->data[i].expn);
}
P->length = m;
}
void PrintPoly(Poly P) {
int i;
for (i = 1; i <= P.length; i++) {
if (i == 1) {
printf("%.2fx^%d", P.data[i].coef, P.data[i].expn);
} else {
printf(" + %.2fx^%d", P.data[i].coef, P.data[i].expn);
}
}
printf("\n");
}
void AddPoly(Poly *Pa, Poly *Pb) {
int i, j, k;
i = j = k = 1;
while (i <= Pa->length && j <= Pb->length) {
if (Pa->data[i].expn == Pb->data[j].expn) {
Pa->data[i].coef += Pb->data[j].coef;
if (Pa->data[i].coef != 0) {
i++;
}
j++;
} else if (Pa->data[i].expn < Pb->data[j].expn) {
i++;
} else {
k = Pa->length;
while (k >= i) {
Pa->data[k + 1] = Pa->data[k];
k--;
}
Pa->data[i] = Pb->data[j];
Pa->length++;
i++;
j++;
}
}
while (j <= Pb->length) {
Pa->data[++Pa->length] = Pb->data[j++];
}
}
void SubtractPoly(Poly *Pa, Poly *Pb) {
int i, j, k;
i = j = k = 1;
while (i <= Pa->length && j <= Pb->length) {
if (Pa->data[i].expn == Pb->data[j].expn) {
Pa->data[i].coef -= Pb->data[j].coef;
if (Pa->data[i].coef != 0) {
i++;
}
j++;
} else if (Pa->data[i].expn < Pb->data[j].expn) {
i++;
} else {
k = Pa->length;
while (k >= i) {
Pa->data[k + 1] = Pa->data[k];
k--;
}
Pa->data[i].coef = -Pb->data[j].coef;
Pa->data[i].expn = Pb->data[j].expn;
Pa->length++;
i++;
j++;
}
}
while (j <= Pb->length) {
Pa->data[++Pa->length].coef = -Pb->data[j].coef;
Pa->data[Pa->length].expn = Pb->data[j].expn;
j++;
}
}
void MultiplyPoly(Poly *Pa, Poly *Pb, Poly *Pc) {
int i, j, k;
for (i = 1; i <= Pa->length; i++) {
for (j = 1; j <= Pb->length; j++) {
k = Pa->data[i].expn + Pb->data[j].expn;
Pc->data[k].coef += Pa->data[i].coef * Pb->data[j].coef;
Pc->data[k].expn = k;
}
}
Pc->length = Pa->length + Pb->length - 1;
}
int main() {
Poly Pa, Pb, Pc;
int m, n;
printf("请输入多项式Pa的项数:");
scanf("%d", &m);
CreatePoly(&Pa, m);
printf("请输入多项式Pb的项数:");
scanf("%d", &n);
CreatePoly(&Pb, n);
printf("Pa = ");
PrintPoly(Pa);
printf("Pb = ");
PrintPoly(Pb);
AddPoly(&Pa, &Pb);
printf("Pa + Pb = ");
PrintPoly(Pa);
SubtractPoly(&Pa, &Pb);
printf("Pa - Pb = ");
PrintPoly(Pa);
MultiplyPoly(&Pa, &Pb, &Pc);
printf("Pa * Pb = ");
PrintPoly(Pc);
return 0;
}
```
阅读全文