用C语言实现线性结构3.一元多项式计算 任务:设计合适的存储结构,完成一元多项式的相关运算。 要求:(1)能够按照指数降序排列建立并输出多项式;(2)能够完成两个多项式的相加、相减,并将结果输出。
时间: 2024-03-12 21:47:30 浏览: 169
以下是一个用C语言实现一元多项式计算的示例程序,其中使用链表作为存储结构:
```c
#include <stdio.h>
#include <stdlib.h>
/* 定义多项式节点 */
typedef struct poly_node {
double coef; // 系数
int expo; // 指数
struct poly_node *next; // 下一个节点指针
} PolyNode, *PolyList;
/* 函数声明 */
void create_poly(PolyList *head); // 创建多项式
void print_poly(PolyList head); // 输出多项式
void add_poly(PolyList head1, PolyList head2, PolyList *result); // 多项式相加
void sub_poly(PolyList head1, PolyList head2, PolyList *result); // 多项式相减
/* 主函数 */
int main() {
PolyList poly1, poly2, result;
printf("请输入第一个多项式:\n");
create_poly(&poly1);
printf("第一个多项式为:");
print_poly(poly1);
printf("\n请输入第二个多项式:\n");
create_poly(&poly2);
printf("第二个多项式为:");
print_poly(poly2);
// 相加并输出结果
add_poly(poly1, poly2, &result);
printf("\n相加后的多项式为:");
print_poly(result);
// 相减并输出结果
sub_poly(poly1, poly2, &result);
printf("\n相减后的多项式为:");
print_poly(result);
return 0;
}
/* 创建多项式 */
void create_poly(PolyList *head) {
PolyNode *p, *q;
int count;
printf("请输入多项式项数:");
scanf("%d", &count);
*head = (PolyNode *) malloc(sizeof(PolyNode));
p = *head;
printf("请输入多项式的系数和指数,按指数降序排列:\n");
for (int i = 0; i < count; ++i) {
q = (PolyNode *) malloc(sizeof(PolyNode));
scanf("%lf%d", &q->coef, &q->expo);
p->next = q;
p = q;
}
p->next = NULL;
}
/* 输出多项式 */
void print_poly(PolyNode *head) {
PolyNode *p = head->next;
if (!p) {
printf("0\n");
return;
}
while (p) {
if (p->coef > 0 && p != head->next) {
printf("+");
}
printf("%.2fx^%d", p->coef, p->expo);
p = p->next;
}
}
/* 多项式相加 */
void add_poly(PolyNode *head1, PolyNode *head2, PolyNode **result) {
PolyNode *p1 = head1->next, *p2 = head2->next, *pr, *r;
*result = (PolyNode *) malloc(sizeof(PolyNode));
pr = *result;
while (p1 && p2) {
r = (PolyNode *) malloc(sizeof(PolyNode));
if (p1->expo > p2->expo) {
r->coef = p1->coef;
r->expo = p1->expo;
p1 = p1->next;
} else if (p1->expo < p2->expo) {
r->coef = p2->coef;
r->expo = p2->expo;
p2 = p2->next;
} else {
r->coef = p1->coef + p2->coef;
r->expo = p1->expo;
p1 = p1->next;
p2 = p2->next;
}
pr->next = r;
pr = r;
}
if (p1) {
pr->next = p1;
} else {
pr->next = p2;
}
}
/* 多项式相减 */
void sub_poly(PolyNode *head1, PolyNode *head2, PolyNode **result) {
PolyNode *p1 = head1->next, *p2 = head2->next, *pr, *r;
*result = (PolyNode *) malloc(sizeof(PolyNode));
pr = *result;
while (p1 && p2) {
r = (PolyNode *) malloc(sizeof(PolyNode));
if (p1->expo > p2->expo) {
r->coef = p1->coef;
r->expo = p1->expo;
p1 = p1->next;
} else if (p1->expo < p2->expo) {
r->coef = -p2->coef;
r->expo = p2->expo;
p2 = p2->next;
} else {
r->coef = p1->coef - p2->coef;
r->expo = p1->expo;
p1 = p1->next;
p2 = p2->next;
}
pr->next = r;
pr = r;
}
if (p1) {
pr->next = p1;
} else {
pr->next = p2;
while (pr->next != NULL) {
pr->next->coef = -pr->next->coef;
pr = pr->next;
}
}
}
```
该程序可以实现创建、输出、相加和相减两个多项式的功能。在输入多项式时需要按指数降序排列,输出时会自动按照指数降序排列并合并同类项。
阅读全文
相关推荐


















