用C语言编写求两个多项式相加的程序。 实验数据: P1(x)=5x8+3x4-2x3+3x+5 P2(x)=7x4+2x3-2x2 P(x)=P1(x)+P2(x)=5x8 +10x4-2x2+3x+5
时间: 2023-11-26 10:04:47 浏览: 128
```c
#include <stdio.h>
#define MAX_DEGREE 10 // 多项式最高阶数为10
// 多项式结构体
typedef struct {
int coef[MAX_DEGREE + 1]; // 系数数组,下标表示该项的指数
int degree; // 最高项次数
} Polynomial;
// 初始化多项式
void initPolynomial(Polynomial *P) {
for (int i = 0; i <= MAX_DEGREE; i++) {
P->coef[i] = 0;
}
P->degree = 0;
}
// 读入多项式
void readPolynomial(Polynomial *P) {
int n, c, d;
initPolynomial(P);
printf("请输入多项式的项数:");
scanf("%d", &n);
printf("请依次输入每一项的系数和指数(用空格分隔):\n");
for (int i = 1; i <= n; i++) {
scanf("%d%d", &c, &d);
P->coef[d] = c;
if (d > P->degree) {
P->degree = d;
}
}
}
// 输出多项式
void printPolynomial(Polynomial P) {
int flag = 0;
for (int i = P.degree; i >= 0; i--) {
if (P.coef[i] != 0) {
if (flag == 1) {
printf("+");
}
printf("%dx%d", P.coef[i], i);
flag = 1;
}
}
printf("\n");
}
// 多项式相加
Polynomial addPolynomial(Polynomial P1, Polynomial P2) {
Polynomial P;
initPolynomial(&P);
P.degree = P1.degree > P2.degree ? P1.degree : P2.degree;
for (int i = P.degree; i >= 0; i--) {
P.coef[i] = P1.coef[i] + P2.coef[i];
}
return P;
}
int main() {
Polynomial P1, P2, P;
readPolynomial(&P1);
readPolynomial(&P2);
P = addPolynomial(P1, P2);
printf("P1(x)=");
printPolynomial(P1);
printf("P2(x)=");
printPolynomial(P2);
printf("P(x)=");
printPolynomial(P);
return 0;
}
```
阅读全文