一元多项式的表示及相加的C语言具体代码
时间: 2024-02-18 22:01:27 浏览: 120
C++实现一元多项式的表示及相加
一元多项式可以使用结构体来表示,其中结构体包括两个成员变量,一个是系数,另一个是指数。下面是一元多项式的结构体定义:
```c
typedef struct node {
float coef; // 系数
int expn; // 指数
struct node *next;
} Polynomial;
```
其中,`next` 是指向下一个结点的指针,可以用来构造链表。
下面是一元多项式相加的具体代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
float coef; // 系数
int expn; // 指数
struct node *next;
} Polynomial;
// 生成多项式
Polynomial *create() {
Polynomial *p, *r, *head;
head = (Polynomial*)malloc(sizeof(Polynomial));
head->next = NULL;
r = head;
int n, i;
float c;
printf("请输入多项式的项数:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
printf("请输入第%d项的系数和指数:", i);
scanf("%f %d", &c, &e);
p = (Polynomial*)malloc(sizeof(Polynomial));
p->coef = c;
p->expn = e;
p->next = NULL;
r->next = p;
r = p;
}
return head;
}
// 多项式相加
Polynomial *add(Polynomial *pa, Polynomial *pb) {
Polynomial *pc, *qa, *qb, *p, *q, *t;
pc = (Polynomial*)malloc(sizeof(Polynomial));
pc->next = NULL;
qa = pa->next;
qb = pb->next;
p = pc;
while (qa && qb) {
if (qa->expn < qb->expn) {
t = (Polynomial*)malloc(sizeof(Polynomial));
t->coef = qa->coef;
t->expn = qa->expn;
t->next = NULL;
p->next = t;
p = t;
qa = qa->next;
} else if (qa->expn > qb->expn) {
t = (Polynomial*)malloc(sizeof(Polynomial));
t->coef = qb->coef;
t->expn = qb->expn;
t->next = NULL;
p->next = t;
p = t;
qb = qb->next;
} else {
t = (Polynomial*)malloc(sizeof(Polynomial));
t->coef = qa->coef + qb->coef;
t->expn = qa->expn;
t->next = NULL;
p->next = t;
p = t;
qa = qa->next;
qb = qb->next;
}
}
while (qa) {
t = (Polynomial*)malloc(sizeof(Polynomial));
t->coef = qa->coef;
t->expn = qa->expn;
t->next = NULL;
p->next = t;
p = t;
qa = qa->next;
}
while (qb) {
t = (Polynomial*)malloc(sizeof(Polynomial));
t->coef = qb->coef;
t->expn = qb->expn;
t->next = NULL;
p->next = t;
p = t;
qb = qb->next;
}
return pc;
}
// 输出多项式
void print(Polynomial *p) {
Polynomial *q = p;
while (q->next) {
q = q->next;
printf("%.2fx^%d", q->coef, q->expn);
if (q->next) {
printf(" + ");
}
}
printf("\n");
}
int main() {
Polynomial *pa, *pb, *pc;
printf("请输入第一个多项式:\n");
pa = create();
printf("请输入第二个多项式:\n");
pb = create();
pc = add(pa, pb);
printf("相加后的多项式为:\n");
print(pc);
return 0;
}
```
此代码中使用了单链表来存储多项式,`create` 函数用来生成多项式,`add` 函数用来实现多项式相加,`print` 函数用来输出多项式。
阅读全文