在C语言中,可以使用数组来表示多项式。数组的下标表示多项式的指数,数组的值表示多项式的系数。
以下是一个示例代码,用于实现两个多项式的加法和减法:
#include <stdio.h>
#define MAX_DEGREE 100
// 多项式结构体
typedef struct {
int degree; // 最高次数
int coeff[MAX_DEGREE + 1]; // 系数数组
} Polynomial;
// 初始化多项式
void initPolynomial(Polynomial *poly) {
poly->degree = 0;
for (int i = 0; i <= MAX_DEGREE; i++) {
poly->coeff[i] = 0;
}
}
// 输入多项式
void inputPolynomial(Polynomial *poly) {
printf("Enter the degree of the polynomial: ");
scanf("%d", &(poly->degree));
printf("Enter the coefficients of the polynomial: ");
for (int i = 0; i <= poly->degree; i++) {
scanf("%d", &(poly->coeff[i]));
}
}
// 打印多项式
void printPolynomial(Polynomial *poly) {
for (int i = poly->degree; i >= 0; i--) {
printf("%dx^%d ", poly->coeff[i], i);
if (i > 0) {
printf("+ ");
}
}
printf("\n");
}
// 多项式加法
Polynomial addPolynomials(Polynomial *poly1, Polynomial *poly2) {
Polynomial sum;
initPolynomial(&sum);
sum.degree = (poly1->degree > poly2->degree) ? poly1->degree : poly2->degree;
for (int i = 0; i <= sum.degree; i++) {
sum.coeff[i] = poly1->coeff[i] + poly2->coeff[i];
}
return sum;
}
// 多项式减法
Polynomial subtractPolynomials(Polynomial *poly1, Polynomial *poly2) {
Polynomial diff;
initPolynomial(&diff);
diff.degree = (poly1->degree > poly2->degree) ? poly1->degree : poly2->degree;
for (int i = 0; i <= diff.degree; i++) {
diff.coeff[i] = poly1->coeff[i] - poly2->coeff[i];
}
return diff;
}
int main() {
Polynomial poly1, poly2, sum, diff;
// 输入多项式1
printf("Enter the first polynomial:\n");
inputPolynomial(&poly1);
// 输入多项式2
printf("Enter the second polynomial:\n");
inputPolynomial(&poly2);
// 计算多项式的和与差
sum = addPolynomials(&poly1, &poly2);
diff = subtractPolynomials(&poly1, &poly2);
// 打印多项式的和与差
printf("Sum: ");
printPolynomial(&sum);
printf("Difference: ");
printPolynomial(&diff);
return 0;
}
这段代码首先定义了一个Polynomial
结构体来表示多项式,包括最高次数和系数数组。然后定义了一些函数来初始化多项式、输入多项式、打印多项式、进行多项式的加法和减法运算。
在main
函数中,首先输入了两个多项式,然后调用addPolynomials
和subtractPolynomials
函数计算多项式的和与差,最后打印出结果。