在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
函數計算多項式的和與差,最后打印出結果。