数据结构一元多项式相加运算c语言完整代码
时间: 2024-10-27 14:00:56 浏览: 46
一元多项式相加-c语言代码-北理乐学
在一元多项式相加的C语言操作中,我们通常会使用数组或链表来表示多项式的系数和指数。下面是一个简单的例子,展示了如何创建两个一元多项式,并通过数组相加:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int coefficient; // 系数
int exponent; // 指数
} Term;
// 功能:一元多项式相加
Term* addPolynomials(Term* poly1, Term* poly2, int degree) {
Term* result = malloc((degree + 1) * sizeof(Term)); // 分配新多项式的空间
result[0].coefficient = 0; // 初始化结果多项式的首项系数为0
for (int i = 0; i <= degree; ++i) {
if (poly1[i].exponent == poly2[i].exponent) {
result[i].coefficient = poly1[i].coefficient + poly2[i].coefficient;
} else if (poly1[i].exponent > poly2[i].exponent) {
result[i].coefficient += poly1[i].coefficient;
result[i+1].exponent = poly1[i].exponent - poly2[i].exponent; // 如果有进位,则更新下一个项的指数
} else {
result[i].coefficient += poly2[i].coefficient;
result[i+1].exponent = poly2[i].exponent - poly1[i].exponent; // 类似于上一行
}
}
return result;
}
void printPolynomial(Term* poly, int degree) {
printf("y = ");
for (int i = 0; i <= degree; ++i) {
if (poly[i].coefficient != 0) {
printf("%d*x^%d + ", poly[i].coefficient, poly[i].exponent);
}
}
printf("0\n");
}
int main() {
Term poly1[] = { {5, 2}, {3, 1}, {0, 0} }; // y = 5x^2 + 3x
Term poly2[] = { {4, 2}, {2, 1}, {0, 0} }; // y = 4x^2 + 2x
int degree = 2; // 这里假设最高次幂不超过2
Term* sum = addPolynomials(poly1, poly2, degree);
printPolynomial(sum, degree);
free(sum); // 别忘了释放内存
return 0;
}
阅读全文