一元多项式加法运算在c语言中如何实现
时间: 2024-09-23 22:05:41 浏览: 78
在C语言中,实现一元多项式加法运算,可以使用数组来存储多项式的系数和使用指针追踪当前项。下面是一个简单的示例,展示了如何创建结构体表示多项式,以及如何计算两个多项式的和:
```c
#include <stdio.h>
// 定义多项式结构体
typedef struct {
int degree; // 最高次数
double* coefficients; // 存放系数
} Polynomial;
// 动态分配空间并初始化多项式
Polynomial create_polynomial(int degree) {
Polynomial poly;
poly.degree = degree;
poly.coefficients = (double*)malloc(degree * sizeof(double));
for (int i = 0; i <= degree; i++) {
if (i == degree || i == 0)
poly.coefficients[i] = 0; // 初始化常数项
else
poly.coefficients[i] = 0; // 非零项暂设为0
}
return poly;
}
// 添加多项式项
void add_coefficient(Polynomial* p1, Polynomial* p2, int index, double value) {
p1->coefficients[index] += p2->coefficients[index];
}
// 计算两个多项式的加法
void polynomial_add(Polynomial* p1, Polynomial* p2, Polynomial* result) {
int max_degree = MAX(p1->degree, p2->degree); // 获取较大的次数
for (int i = 0; i <= max_degree; i++) {
if (p1->coefficients[i] != 0 || p2->coefficients[i] != 0)
add_coefficient(result, p1, i, p1->coefficients[i]);
add_coefficient(result, p2, i, p2->coefficients[i]);
}
result->degree = max_degree;
}
// 打印多项式
void print_polynomial(Polynomial poly) {
printf("Polynomial: ");
for (int i = poly.degree; i >= 0; i--) {
printf("%d*x^%d + ", (int)(poly.coefficients[i]*100), i);
}
printf("Constant term\n");
}
int main() {
Polynomial p1 = create_polynomial(2); // 初始化多项式1
Polynomial p2 = create_polynomial(2); // 初始化多项式2
// 设置多项式系数
p1.coefficients[0] = 3;
p1.coefficients[1] = -5;
p2.coefficients[0] = -2;
p2.coefficients[1] = 4;
Polynomial result = create_polynomial(2); // 结果多项式
polynomial_add(&p1, &p2, &result);
print_polynomial(result);
free(p1.coefficients);
free(p2.coefficients);
free(result.coefficients);
return 0;
}
```
阅读全文