要求:用c语言实现代码,将一元多项式采用单链表存储结构,实现如下功能: 1)从键盘输人一元多项式的各项系数和指数,创建一 元多项式链表;2)输出一元多项式; 3)任意输入的两个多项式相加,求和多项式. 4)任意输人的两个多项式相减,求差多项式。
时间: 2024-10-08 22:23:47 浏览: 34
在C语言中,我们可以使用结构体表示多项式项,并使用链表的数据结构来存储多项式。这里是一个简单的实现,包括了创建、显示和操作多项式的功能:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
double coef; // 系数
int exp; // 指数
} PolynomialTerm;
typedef struct {
PolynomialTerm* terms;
int count;
} Polynomial;
// 创建新的多项式项
PolynomialTerm* new_term(double coef, int exp) {
PolynomialTerm* term = (PolynomialTerm*)malloc(sizeof(PolynomialTerm));
term->coef = coef;
term->exp = exp;
return term;
}
// 添加新项到多项式
void add_term(Polynomial* poly, double coef, int exp) {
PolynomialTerm* new = new_term(coef, exp);
if (poly->count == 0) {
poly->terms = new;
} else {
poly->terms[poly->count - 1].next = new;
}
poly->count++;
}
// 显示多项式
void display_polynomial(Polynomial poly) {
for (int i = poly.count - 1; i >= 0; i--) {
printf("%f * x^%d + ", poly.terms[i].coef, poly.terms[i].exp);
}
printf("0\n");
}
// 多项式相加
Polynomial add_poly(Polynomial poly1, Polynomial poly2) {
Polynomial result = {NULL, 0};
for (int i = 0; i < poly1.count || i < poly2.count; i++) {
if (i < poly1.count && i < poly2.count) {
PolynomialTerm* sum_term = new_term(poly1.terms[i].coef + poly2.terms[i].coef, poly1.terms[i].exp);
} else if (i < poly1.count) {
PolynomialTerm* term = poly1.terms[i];
} else {
PolynomialTerm* term = poly2.terms[i - poly1.count];
}
result.count++;
result.terms = realloc(result.terms, sizeof(PolynomialTerm*) * (result.count + 1));
result.terms[result.count - 1] = term;
}
return result;
}
// 主函数
int main() {
Polynomial poly1, poly2;
while (true) {
char choice;
printf("1. 输入多项式并添加\n2. 显示多项式\n3. 加法多项式\n4. 减法多项式\n5. 退出\n");
scanf(" %c", &choice);
switch (choice) {
case '1':
double coef, exp;
printf("请输入系数和指数,以空格分隔:");
scanf("%lf %d", &coef, &exp);
add_term(&poly1, coef, exp);
break;
case '2':
display_polynomial(poly1);
break;
case '3':
if (poly1.count > 0 && poly2.count > 0) {
Polynomial result = add_poly(poly1, poly2);
display_polynomial(result);
} else {
printf("请输入两个非空多项式进行加法操作。\n");
}
break;
case '4':
if (poly1.count > 0 && poly2.count > 0) {
Polynomial result = {NULL, 0};
for (int i = 0; i < poly1.count; i++) {
PolynomialTerm* diff_term = new_term(poly1.terms[i].coef - poly2.terms[i].coef, poly1.terms[i].exp);
result.count++;
result.terms = realloc(result.terms, sizeof(PolynomialTerm*) * (result.count + 1));
result.terms[result.count - 1] = diff_term;
}
display_polynomial(result);
} else {
printf("请输入两个非空多项式进行减法操作。\n");
}
break;
case '5':
exit(0);
default:
printf("无效选择,请再试一次。\n");
}
}
return 0;
}
```
这个程序会提示用户选择操作,输入多项式,显示多项式,以及对两个多项式进行加法和减法。注意,为了简化示例,我们假设用户总是输入有效的数据。实际应用中应增加错误处理。
阅读全文