编程实现一元多项式的加法运算。第一个一元多项式A; 第二个一元多项式B。 以(0,0)作为输入结束。多项式A和多项式B的和。C语言
时间: 2023-05-29 10:05:35 浏览: 101
c语言 两个一元多项式相加。
#include <stdio.h>
#define MAX_TERM 100
typedef struct {
float coeff; // 系数
int exp; // 指数
} Term;
typedef struct {
Term termArray[MAX_TERM];
int numTerms;
} Polynomial;
// 从标准输入读取多项式的项
void readPoly(Polynomial *poly) {
int i = 0;
float coeff;
int exp;
printf("输入多项式的系数和指数(输入 0 0 结束):\n");
do {
scanf("%f %d", &coeff, &exp);
if (coeff == 0 || exp == 0) break;
poly->termArray[i].coeff = coeff;
poly->termArray[i].exp = exp;
i++;
} while (i < MAX_TERM);
poly->numTerms = i;
}
// 打印多项式
void printPoly(Polynomial poly) {
printf("多项式:\n");
for (int i = 0; i < poly.numTerms; i++) {
printf("%.2fx^%d", poly.termArray[i].coeff, poly.termArray[i].exp);
if (i < poly.numTerms - 1) printf(" + ");
}
printf("\n");
}
// 一元多项式加法
Polynomial addPoly(Polynomial poly1, Polynomial poly2) {
Polynomial result;
int i = 0, j = 0, k = 0;
while (i < poly1.numTerms && j < poly2.numTerms) {
if (poly1.termArray[i].exp > poly2.termArray[j].exp) {
result.termArray[k++] = poly1.termArray[i++];
} else if (poly1.termArray[i].exp < poly2.termArray[j].exp) {
result.termArray[k++] = poly2.termArray[j++];
} else {
result.termArray[k].coeff = poly1.termArray[i].coeff + poly2.termArray[j].coeff;
result.termArray[k++].exp = poly1.termArray[i++].exp;
j++;
}
}
while (i < poly1.numTerms) {
result.termArray[k++] = poly1.termArray[i++];
}
while (j < poly2.numTerms) {
result.termArray[k++] = poly2.termArray[j++];
}
result.numTerms = k;
return result;
}
int main() {
Polynomial poly1, poly2, result;
readPoly(&poly1);
readPoly(&poly2);
printPoly(poly1);
printPoly(poly2);
result = addPoly(poly1, poly2);
printPoly(result);
return 0;
}
阅读全文