用C语言实现多项式的相加
时间: 2024-10-10 21:16:14 浏览: 69
在C语言中,你可以使用结构体来表示一个多项式,并通过链表的方式来存储多项式的系数和对应的次数。下面是一个简单的多项式相加的实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Term {
int coefficient; // 系数
int exponent; // 次数
} Term;
typedef struct Polynomial {
Term* terms;
int count;
} Polynomial;
// 创建一个新的多项式项
Term* create_term(int coefficient, int exponent) {
Term* new_term = (Term*)malloc(sizeof(Term));
if (new_term != NULL) {
new_term->coefficient = coefficient;
new_term->exponent = exponent;
}
return new_term;
}
// 初始化多项式
Polynomial* create_polynomial() {
Polynomial* poly = (Polynomial*)malloc(sizeof(Polynomial));
if (poly != NULL) {
poly->terms = NULL;
poly->count = 0;
}
return poly;
}
// 添加多项式项到链表
void add_term(Polynomial* poly, int coefficient, int exponent) {
if (poly == NULL || poly->count == 0) {
poly->terms = create_term(coefficient, exponent);
poly->count++;
} else {
Term* last = poly->terms;
while (last->next != NULL && last->exponent > exponent) {
last = last->next;
}
if (last->exponent == exponent) {
last->coefficient += coefficient;
} else {
last->next = create_term(coefficient, exponent);
poly->count++;
}
}
}
// 相加两个多项式
Polynomial* add_poly(Polynomial* poly1, Polynomial* poly2) {
Polynomial* result = create_polynomial();
if (poly1 != NULL && poly2 != NULL) {
for (int i = 0; i < poly1->count; i++) {
add_term(result, poly1->terms[i].coefficient, poly1->terms[i].exponent);
}
for (int i = 0; i < poly2->count; i++) {
add_term(result, poly2->terms[i].coefficient, poly2->terms[i].exponent);
}
}
return result;
}
// 打印多项式
void print_polynomial(Polynomial* poly) {
printf("Polynomial:\n");
if (poly->terms == NULL) {
printf("Constant term: %d\n", poly->terms[0].coefficient); // 如果只有一个常数项
} else {
for (Term* term = poly->terms; term != NULL; term = term->next) {
printf("%d * x^%d + ", term->coefficient, term->exponent);
}
printf("\n"); // 最后打印换行
}
}
int main() {
Polynomial* p1 = create_polynomial();
Polynomial* p2 = create_polynomial();
// 添加多项式项
add_term(p1, 2, 1);
add_term(p1, -1, 2);
add_term(p2, 3, 0);
Polynomial* sum = add_poly(p1, p2);
print_polynomial(sum);
free(p1->terms);
free(p1);
free(p2->terms);
free(p2);
free(sum->terms);
free(sum);
return 0;
}
```
在这个例子中,我们首先创建了两个`Polynomial`结构体实例,并分别添加了一些项。然后通过`add_poly`函数将它们相加,最后打印出结果。
阅读全文