C语言实现一元多项式的表示和实现
时间: 2024-02-05 17:13:14 浏览: 81
C语言实现一元多项式相加
一元多项式可以表示为:
a0 + a1*x + a2*x^2 + ... + an*x^n
其中 a0, a1, ..., an 为系数,n 为最高次数,x 为未知数。
实现一元多项式可以定义一个结构体,包含系数和次数两个成员变量。具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node *PtrToNode;
typedef PtrToNode Polynomial;
struct Node {
int coef; // 系数
int expon; // 次数
Polynomial Next;
};
Polynomial CreatePoly(); // 创建多项式
Polynomial AddPoly(Polynomial P1, Polynomial P2); // 多项式相加
void PrintPoly(Polynomial P); // 输出多项式
int main()
{
Polynomial P1, P2, PP;
printf("创建第一个多项式:\n");
P1 = CreatePoly();
printf("第一个多项式:");
PrintPoly(P1);
printf("创建第二个多项式:\n");
P2 = CreatePoly();
printf("第二个多项式:");
PrintPoly(P2);
PP = AddPoly(P1, P2);
printf("两个多项式相加的结果为:");
PrintPoly(PP);
return 0;
}
Polynomial CreatePoly()
{
Polynomial P, Rear, t;
int c, e;
P = (Polynomial)malloc(sizeof(struct Node));
P->Next = NULL;
Rear = P;
printf("请输入多项式系数和指数,以 -1 -1 结束\n");
scanf("%d %d", &c, &e);
while (c != -1) {
t = (Polynomial)malloc(sizeof(struct Node));
t->coef = c;
t->expon = e;
t->Next = NULL;
Rear->Next = t;
Rear = t;
scanf("%d %d", &c, &e);
}
return P;
}
Polynomial AddPoly(Polynomial P1, Polynomial P2)
{
Polynomial Front, Rear, temp;
int sum;
Front = (Polynomial)malloc(sizeof(struct Node));
Rear = Front;
P1 = P1->Next;
P2 = P2->Next;
while (P1 && P2) {
if (P1->expon == P2->expon) {
sum = P1->coef + P2->coef;
if (sum) {
temp = (Polynomial)malloc(sizeof(struct Node));
temp->coef = sum;
temp->expon = P1->expon;
Rear->Next = temp;
Rear = temp;
}
P1 = P1->Next;
P2 = P2->Next;
} else if (P1->expon > P2->expon) {
temp = (Polynomial)malloc(sizeof(struct Node));
temp->coef = P1->coef;
temp->expon = P1->expon;
Rear->Next = temp;
Rear = temp;
P1 = P1->Next;
} else {
temp = (Polynomial)malloc(sizeof(struct Node));
temp->coef = P2->coef;
temp->expon = P2->expon;
Rear->Next = temp;
Rear = temp;
P2 = P2->Next;
}
}
while (P1) {
temp = (Polynomial)malloc(sizeof(struct Node));
temp->coef = P1->coef;
temp->expon = P1->expon;
Rear->Next = temp;
Rear = temp;
P1 = P1->Next;
}
while (P2) {
temp = (Polynomial)malloc(sizeof(struct Node));
temp->coef = P2->coef;
temp->expon = P2->expon;
Rear->Next = temp;
Rear = temp;
P2 = P2->Next;
}
Rear->Next = NULL;
temp = Front;
Front = Front->Next;
free(temp);
return Front;
}
void PrintPoly(Polynomial P)
{
int flag = 0;
if (!P) {
printf("0 0\n");
return;
}
while (P) {
if (!flag) {
flag = 1;
} else {
printf(" ");
}
printf("%d %d", P->coef, P->expon);
P = P->Next;
}
printf("\n");
}
```
以上代码中,CreatePoly() 函数用于创建多项式,AddPoly() 函数用于相加两个多项式,PrintPoly() 函数用于输出多项式。
在主函数中,先分别创建两个多项式,然后将它们相加,最后输出结果。
阅读全文