如何用C语言编写一个程序,用单链表存储两个自定义的一元多项式,每次都可以输入不同的一元多项式进行存储
时间: 2024-11-15 18:31:43 浏览: 5
在C语言中,我们可以定义一个结构体来表示多项式项,并使用单向链表来存储这两个多项式。下面是一个简单的示例,包含了创建链表节点、添加项、读取用户输入并存储多项式等功能:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式项结构体
typedef struct Term {
double coefficient; // 系数
int exponent; // 指数
struct Term* next; // 指向下一个项的指针
} Term;
// 功能:创建新项
Term* create_term(double coef, int exp) {
Term* new_term = (Term*)malloc(sizeof(Term));
new_term->coefficient = coef;
new_term->exponent = exp;
new_term->next = NULL;
return new_term;
}
// 功能:合并多项式
void merge_polynomials(Term** poly1, Term** poly2) {
if (*poly1 == NULL) {
*poly1 = *poly2;
} else {
Term* current1 = *poly1;
while (current1->next != NULL) {
current1 = current1->next;
}
current1->next = *poly2;
}
}
// 主函数
int main() {
Term* poly1 = NULL, *poly2 = NULL;
// 循环读取用户输入并添加至链表
for (;;) {
printf("Enter the coefficients and exponents for polynomial 1 (separated by space, enter 'done' to finish): ");
char input[50];
fgets(input, sizeof(input), stdin);
if (strcmp(input, "done") == 0) break;
double coef1, exp1;
sscanf(input, "%lf %d", &coef1, &exp1);
// 创建新项并添加到poly1
Term* term1 = create_term(coef1, exp1);
if (poly1 == NULL) {
poly1 = term1;
} else {
Term* current1 = poly1;
while (current1->next != NULL) {
current1 = current1->next;
}
current1->next = term1;
}
}
// 同样的过程,用于多项式2
for (;;) {
printf("Enter the coefficients and exponents for polynomial 2 (separated by space, enter 'done' to finish): ");
fgets(input, sizeof(input), stdin);
if (strcmp(input, "done") == 0) break;
double coef2, exp2;
sscanf(input, "%lf %d", &coef2, &exp2);
Term* term2 = create_term(coef2, exp2);
if (poly2 == NULL) {
poly2 = term2;
} else {
Term* current2 = poly2;
while (current2->next != NULL) {
current2 = current2->next;
}
current2->next = term2;
}
}
// 合并两个多项式
merge_polynomials(&poly1, &poly2);
// 打印合并后的多项式
printf("\nPolynomial 1 + Polynomial 2:\n");
print_polynomial(poly1);
return 0;
}
// 功能:打印多项式
void print_polynomial(Term* poly) {
while (poly != NULL) {
printf("%.2f*x^%d ", poly->coefficient, poly->exponent);
poly = poly->next;
}
printf("\n");
}
```
在这个程序中,用户可以循环输入一元多项式的每一项,直到输入"done"为止。最后,我们合并两个多项式并将其打印出来。注意这个示例假设输入的都是合法的一元多项式项。在实际应用中,你还需要处理异常情况,比如非数字输入等。
阅读全文