用c语言设计一个完整的多项式相加代码,结果需要过滤掉指数为0的单项式和系数为1且指数为1的单项式
时间: 2023-05-27 08:07:33 浏览: 71
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_TERMS 100
typedef struct {
float coef;
int exp;
} Term;
void readPolynomial(Term poly[]);
void printPolynomial(Term poly[]);
void addPolynomial(Term poly1[], Term poly2[], Term result[]);
int main()
{
Term poly1[MAX_TERMS], poly2[MAX_TERMS], result[MAX_TERMS];
printf("Enter the first polynomial:\n");
readPolynomial(poly1);
printf("Enter the second polynomial:\n");
readPolynomial(poly2);
addPolynomial(poly1, poly2, result);
printf("Result:\n");
printPolynomial(result);
return 0;
}
void readPolynomial(Term poly[])
{
int i, n;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Enter the coefficient and exponent for each term:\n");
for (i = 0; i < n; i++) {
scanf("%f %d", &poly[i].coef, &poly[i].exp);
}
}
void printPolynomial(Term poly[])
{
int i, n;
n = sizeof(poly) / sizeof(poly[0]);
for (i = 0; i < n; i++) {
if (poly[i].coef != 0 && poly[i].exp != 0) {
if (poly[i].coef == 1 && poly[i].exp == 1) {
printf("x ");
} else if (poly[i].coef == -1 && poly[i].exp == 1) {
printf("-x ");
} else if (poly[i].coef == 1 && poly[i].exp != 1) {
printf("x^%d ", poly[i].exp);
} else if (poly[i].coef == -1 && poly[i].exp != 1) {
printf("-x^%d ", poly[i].exp);
} else if (poly[i].exp == 1) {
printf("%+.2fx ", poly[i].coef);
} else {
printf("%+.2fx^%d ", poly[i].coef, poly[i].exp);
}
}
}
printf("\n");
}
void addPolynomial(Term poly1[], Term poly2[], Term result[])
{
int i, j, k, n1, n2;
n1 = sizeof(poly1) / sizeof(poly1[0]);
n2 = sizeof(poly2) / sizeof(poly2[0]);
i = j = k = 0;
while (i < n1 && j < n2) {
if (poly1[i].exp == poly2[j].exp) {
float sum = poly1[i].coef + poly2[j].coef;
if (sum != 0) {
result[k].coef = sum;
result[k].exp = poly1[i].exp;
k++;
}
i++;
j++;
} else if (poly1[i].exp > poly2[j].exp) {
result[k].coef = poly1[i].coef;
result[k].exp = poly1[i].exp;
k++;
i++;
} else {
result[k].coef = poly2[j].coef;
result[k].exp = poly2[j].exp;
k++;
j++;
}
}
while (i < n1) {
result[k].coef = poly1[i].coef;
result[k].exp = poly1[i].exp;
k++;
i++;
}
while (j < n2) {
result[k].coef = poly2[j].coef;
result[k].exp = poly2[j].exp;
k++;
j++;
}
}
```
阅读全文