用C语言实现一元多项式的运算的算法,步骤是创建一个新数组c 分别从头遍历比较a和b的每一项 指数相同,对应系数相加,若其和不为零,则在c中增加一个新项 指数不相同,则将指数较小的项复制到c中 一个多项式已遍历完毕时,将另一个剩余项依次复制到c中即可
时间: 2023-05-24 12:06:58 浏览: 97
#include <stdio.h>
#include <stdlib.h>
#define MAX_TERMS 100
typedef struct {
float coef;
int exp;
} Term;
void readPoly(Term *poly, int *n); // 读取多项式
void printPoly(const Term *poly, int n); // 输出多项式
void addPoly(const Term *a, int na, const Term *b, int nb, Term *c, int *nc); // 多项式求和
int main(void) {
Term a[MAX_TERMS], b[MAX_TERMS], c[MAX_TERMS];
int na, nb, nc;
printf("请输入第一个多项式(系数和指数之间用空格隔开,以0 0为结束符):\n");
readPoly(a, &na);
printf("请输入第二个多项式(系数和指数之间用空格隔开,以0 0为结束符):\n");
readPoly(b, &nb);
addPoly(a, na, b, nb, c, &nc);
printf("第一个多项式为:");
printPoly(a, na);
printf("\n");
printf("第二个多项式为:");
printPoly(b, nb);
printf("\n");
printf("它们的和为:");
printPoly(c, nc);
printf("\n");
return 0;
}
void readPoly(Term *poly, int *n) {
int i = 0;
printf("请输入第%d项的系数和指数:", i + 1);
scanf("%f %d", &poly[i].coef, &poly[i].exp);
while (poly[i].coef != 0 && poly[i].exp != 0 && i < MAX_TERMS - 1) {
i++;
printf("请输入第%d项的系数和指数:", i + 1);
scanf("%f %d", &poly[i].coef, &poly[i].exp);
}
*n = i;
}
void printPoly(const Term *poly, int n) {
int i;
for (i = 0; i < n; i++) {
if (poly[i].exp == 0) {
printf("%g", poly[i].coef);
} else if (poly[i].exp == 1) {
printf("%gx", poly[i].coef);
} else {
printf("%gx^%d", poly[i].coef, poly[i].exp);
}
if (i < n - 1) {
printf(" + ");
}
}
}
void addPoly(const Term *a, int na, const Term *b, int nb, Term *c, int *nc) {
int i = 0, j = 0, k = 0;
while (i < na && j < nb) {
if (a[i].exp == b[j].exp) {
float coef = a[i].coef + b[j].coef;
if (coef != 0) {
c[k].coef = coef;
c[k].exp = a[i].exp;
k++;
}
i++;
j++;
} else if (a[i].exp > b[j].exp) {
c[k].coef = a[i].coef;
c[k].exp = a[i].exp;
i++;
k++;
} else {
c[k].coef = b[j].coef;
c[k].exp = b[j].exp;
j++;
k++;
}
}
while (i < na) {
c[k].coef = a[i].coef;
c[k].exp = a[i].exp;
i++;
k++;
}
while (j < nb) {
c[k].coef = b[j].coef;
c[k].exp = b[j].exp;
j++;
k++;
}
*nc = k;
}
阅读全文