用c语言实现两个一元多项式相加
时间: 2024-12-23 18:24:20 浏览: 24
在C语言中,你可以通过结构体来表示一元多项式,并设计函数来实现两个多项式的相加。下面是一个简单的例子:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式结构体
typedef struct {
int coefficient; // 系数
int degree; // 次数
} Polynomial;
// 动态分配空间存储多项式
Polynomial* create_polynomial(int degree) {
Polynomial* poly = (Polynomial*)malloc(sizeof(Polynomial));
poly->coefficient = 0;
poly->degree = degree;
return poly;
}
// 相加两个多项式
void add_poly(Polynomial* poly1, Polynomial* poly2, Polynomial** result) {
*result = create_polynomial(max(poly1->degree, poly2->degree)); // 创建结果多项式的空间
for (int i = 0; i <= (*result)->degree; ++i) {
if (i <= poly1->degree && poly1->coefficient != 0)
(*result)->coefficient += poly1->coefficient;
if (i <= poly2->degree && poly2->coefficient != 0)
(*result)->coefficient += poly2->coefficient;
}
}
// 打印多项式
void print_poly(Polynomial* poly) {
printf("P(x) = %d * x^%d + ", poly->coefficient, poly->degree);
if (poly->degree > 0)
print_poly(create_polynomial(--poly->degree));
else
printf("0\n");
}
int main() {
Polynomial* poly1 = create_polynomial(2);
Polynomial* poly2 = create_polynomial(3);
poly1->coefficient = 4;
poly1->degree = 2;
poly2->coefficient = -2;
poly2->degree = 3;
Polynomial* sum_poly = NULL;
add_poly(poly1, poly2, &sum_poly);
printf("First polynomial: P1(x) = ");
print_poly(poly1);
printf("Second polynomial: P2(x) = ");
print_poly(poly2);
printf("Sum: P3(x) = ");
print_poly(sum_poly);
free(sum_poly); // 释放内存
free(poly1);
free(poly2);
return 0;
}
```
在这个程序中,我们首先创建了`create_polynomial`函数用于动态分配多项式的存储空间,然后是`add_poly`函数实现了两个多项式的相加,最后有`print_poly`函数用来展示结果。在`main`函数中,我们实例化了两个多项式并进行了相加操作。
阅读全文