c语言编写一个程序实现两个一元多项式相乘
时间: 2023-07-13 14:31:28 浏览: 120
C语言课程设计一元多项式.doc
下面给出一个C语言程序实现两个一元多项式相乘的功能:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
float coef; // 系数
int expn; // 指数
} ElemType, PolyNode;
typedef struct {
PolyNode data[MAXSIZE];
int length;
} PolyList;
void CreatePoly(PolyList *L) {
printf("请输入多项式的项数:");
scanf("%d", &L->length);
printf("请按指数递减的顺序输入各项系数:\n");
for (int i = 0; i < L->length; i++) {
scanf("%f%d", &L->data[i].coef, &L->data[i].expn);
}
}
void PrintPoly(PolyList L) {
printf("多项式为:");
for (int i = 0; i < L.length; i++) {
if (i == 0) {
printf("%.2f*x^%d", L.data[i].coef, L.data[i].expn);
} else {
printf(" + %.2f*x^%d", L.data[i].coef, L.data[i].expn);
}
}
printf("\n");
}
void AddPoly(PolyList *La, PolyList Lb) {
int i, j, k;
i = j = k = 0;
while (i < La->length && j < Lb.length) {
if (La->data[i].expn == Lb.data[j].expn) {
La->data[i].coef += Lb.data[j].coef;
i++;
j++;
} else if (La->data[i].expn < Lb.data[j].expn) {
i++;
} else {
for (int n = La->length - 1; n >= i; n--) {
La->data[n + 1] = La->data[n];
}
La->data[i] = Lb.data[j];
La->length++;
i++;
j++;
}
}
while (j < Lb.length) {
La->data[i++] = Lb.data[j++];
La->length++;
}
}
void MultiplyPoly(PolyList La, PolyList Lb, PolyList *Lc) {
PolyNode temp[MAXSIZE];
int i, j, k, n;
float temp_coef;
Lc->length = 0;
for (i = 0; i < La.length; i++) {
for (j = 0; j < Lb.length; j++) {
temp_coef = La.data[i].coef * Lb.data[j].coef;
n = La.data[i].expn + Lb.data[j].expn;
temp[n].coef += temp_coef;
temp[n].expn = n;
}
}
for (k = 0; k < MAXSIZE; k++) {
if (temp[k].coef != 0) {
Lc->data[Lc->length] = temp[k];
Lc->length++;
}
}
}
int main() {
PolyList La, Lb, Lc;
CreatePoly(&La);
CreatePoly(&Lb);
printf("\n");
PrintPoly(La);
PrintPoly(Lb);
AddPoly(&La, Lb);
printf("\n");
PrintPoly(La);
MultiplyPoly(La, Lb, &Lc);
printf("\n");
PrintPoly(Lc);
return 0;
}
```
程序中使用了线性表来存储多项式,其中 `PolyNode` 结构体表示多项式的一项,`PolyList` 结构体表示整个多项式。程序中先输入两个多项式,然后将它们相加并输出,最后将它们相乘并输出。
阅读全文