亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

C語言怎么實現多項式加減

小億
131
2023-08-17 22:11:40
欄目: 編程語言

在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函數中,首先輸入了兩個多項式,然后調用addPolynomialssubtractPolynomials函數計算多項式的和與差,最后打印出結果。

0
遂川县| 缙云县| 阜新市| 青川县| 陕西省| 周口市| 秦皇岛市| 九龙城区| 梁平县| 凤山市| 福建省| 通渭县| 昌图县| 高唐县| 龙山县| 揭阳市| 黄梅县| 德州市| 宁都县| 农安县| 遵化市| 无极县| 阿坝县| 衡阳市| 永济市| 阿图什市| 伊宁县| 博白县| 咸宁市| 娱乐| 梁河县| 宁化县| 渭源县| 新密市| 托克逊县| 民权县| 塘沽区| 大冶市| 吴忠市| 明水县| 龙海市|