c语言实现一元多项式的加法运算
时间: 2023-11-25 07:07:27 浏览: 114
#include <stdio.h>
#include <stdlib.h>
#define MAX_DEGREE 100 // 多项式最大次数
typedef struct {
int degree; // 多项式次数
int coef[MAX_DEGREE + 1]; // 多项式系数,下标对应次数
} Polynomial;
// 初始化多项式
void initPoly(Polynomial *poly) {
int i;
poly->degree = 0;
for (i = 0; i <= MAX_DEGREE; i++) {
poly->coef[i] = 0;
}
}
// 输入多项式
void inputPoly(Polynomial *poly) {
int i;
printf("请输入多项式的次数:");
scanf("%d", &poly->degree);
printf("请输入多项式的系数(从高到低):");
for (i = poly->degree; i >= 0; i--) {
scanf("%d", &poly->coef[i]);
}
}
// 输出多项式
void outputPoly(Polynomial *poly) {
int i;
printf("多项式为:");
for (i = poly->degree; i >= 0; i--) {
if (poly->coef[i] != 0) {
if (i == poly->degree) {
printf("%d", poly->coef[i]);
} else if (i == 0) {
if (poly->coef[i] > 0) {
printf("+%d", poly->coef[i]);
} else if (poly->coef[i] < 0) {
printf("%d", poly->coef[i]);
}
} else {
if (poly->coef[i] > 0) {
printf("+%dx^%d", poly->coef[i], i);
} else if (poly->coef[i] < 0) {
printf("%dx^%d", poly->coef[i], i);
}
}
}
}
printf("\n");
}
// 多项式相加
Polynomial addPoly(Polynomial *p1, Polynomial *p2) {
Polynomial sum;
int i;
initPoly(&sum);
sum.degree = (p1->degree > p2->degree) ? p1->degree : p2->degree;
for (i = 0; i <= sum.degree; i++) {
sum.coef[i] = p1->coef[i] + p2->coef[i];
}
return sum;
}
int main() {
Polynomial p1, p2, sum;
initPoly(&p1);
initPoly(&p2);
initPoly(&sum);
printf("请输入第一个多项式:\n");
inputPoly(&p1);
outputPoly(&p1);
printf("请输入第二个多项式:\n");
inputPoly(&p2);
outputPoly(&p2);
sum = addPoly(&p1, &p2);
printf("两个多项式相加的结果为:\n");
outputPoly(&sum);
return 0;
}
阅读全文