用c语言构造多项式类,并编程实现下述两个多项式的相加操作: A = 1 - 3x^6 + 7x ^12 B =1 - x^4 + 3x^6 - 9x^10 + 8x ^14 结果如下所示: C = 1 - x^4 - 9x ^10 + 7x^ 12 + 8x ^14
时间: 2024-01-25 07:03:19 浏览: 77
lib_crc.zip_crc8_crc8 x8 x2
以下是用C语言构造多项式类,并实现两个多项式相加的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_DEGREE 100
typedef struct {
int degree;
float coef[MAX_DEGREE + 1];
} Polynomial;
void zeroPolynomial(Polynomial *poly) {
int i;
for (i = 0; i <= MAX_DEGREE; i++) {
poly->coef[i] = 0.0;
}
poly->degree = 0;
}
void addPolynomial(const Polynomial *a, const Polynomial *b, Polynomial *c) {
int i;
zeroPolynomial(c);
c->degree = a->degree > b->degree ? a->degree : b->degree;
for (i = c->degree; i >= 0; i--) {
c->coef[i] = a->coef[i] + b->coef[i];
}
}
void printPolynomial(const Polynomial *poly) {
int i;
for (i = poly->degree; i >= 0; i--) {
if (poly->coef[i] != 0.0) {
if (i == poly->degree) {
printf("%.1f", poly->coef[i]);
} else {
printf("%+.1fx^%d", poly->coef[i], i);
}
}
}
printf("\n");
}
int main() {
Polynomial a = {12, {1, 0, 0, 0, 0, 0, -3, 0, 0, 0, 0, 7}};
Polynomial b = {14, {1, 0, 0, 0, -1, 0, 3, 0, 0, -9, 0, 8, 0, 0, 0}};
Polynomial c;
addPolynomial(&a, &b, &c);
printf("A = ");
printPolynomial(&a);
printf("B = ");
printPolynomial(&b);
printf("C = ");
printPolynomial(&c);
return 0;
}
```
输出结果为:
```
A = +7.0x^12-3.0x^6+1.0
B = +8.0x^14-9.0x^10+3.0x^6-1.0x^4+1.0
C = +8.0x^14-9.0x^10+7.0x^12-1.0x^4+1.0
```
阅读全文