要實現C語言中的多項式計算,可以采用以下步驟:
定義多項式的數據結構,可以使用數組或鏈表來表示多項式的每一項。每一項可以包括系數和指數。
typedef struct {
int coefficient; // 系數
int exponent; // 指數
} Term;
typedef struct {
Term terms[MAX_TERMS]; // 多項式的項
int count; // 多項式的項數
} Polynomial;
實現多項式的輸入函數,用來從用戶輸入中獲取多項式的系數和指數,并將其保存到多項式的數據結構中。
void input(Polynomial *poly) {
printf("輸入多項式的項數:");
scanf("%d", &(poly->count));
printf("輸入多項式的系數和指數:\n");
for (int i = 0; i < poly->count; i++) {
printf("第%d項:", i + 1);
scanf("%d %d", &(poly->terms[i].coefficient), &(poly->terms[i].exponent));
}
}
實現多項式的加法函數,用來將兩個多項式相加,并將結果保存到第一個多項式中。
void add(Polynomial *poly1, Polynomial *poly2) {
int i = 0, j = 0, k = 0;
while (i < poly1->count && j < poly2->count) {
if (poly1->terms[i].exponent > poly2->terms[j].exponent) {
poly1->terms[k++] = poly1->terms[i++];
} else if (poly1->terms[i].exponent < poly2->terms[j].exponent) {
poly1->terms[k++] = poly2->terms[j++];
} else {
poly1->terms[k].coefficient = poly1->terms[i].coefficient + poly2->terms[j].coefficient;
poly1->terms[k++].exponent = poly1->terms[i].exponent;
i++;
j++;
}
}
for (; i < poly1->count; i++) {
poly1->terms[k++] = poly1->terms[i];
}
for (; j < poly2->count; j++) {
poly1->terms[k++] = poly2->terms[j];
}
poly1->count = k;
}
實現多項式的乘法函數,用來將兩個多項式相乘,并將結果保存到第一個多項式中。
void multiply(Polynomial *poly1, Polynomial *poly2) {
Polynomial temp;
temp.count = 0;
for (int i = 0; i < poly1->count; i++) {
for (int j = 0; j < poly2->count; j++) {
temp.terms[temp.count].coefficient = poly1->terms[i].coefficient * poly2->terms[j].coefficient;
temp.terms[temp.count].exponent = poly1->terms[i].exponent + poly2->terms[j].exponent;
temp.count++;
}
}
for (int i = 0; i < temp.count; i++) {
for (int j = i + 1; j < temp.count; j++) {
if (temp.terms[i].exponent == temp.terms[j].exponent) {
temp.terms[i].coefficient += temp.terms[j].coefficient;
temp.terms[j].coefficient = 0;
}
}
}
int k = 0;
for (int i = 0; i < temp.count; i++) {
if (temp.terms[i].coefficient != 0) {
poly1->terms[k++] = temp.terms[i];
}
}
poly1->count = k;
}
實現多項式的輸出函數,用來將多項式的內容輸出到屏幕上。
void display(Polynomial *poly) {
printf("多項式的項數:%d\n", poly->count);
for (int i = 0; i < poly->count; i++) {
printf("%dx^%d ", poly->terms[i].coefficient, poly->terms