中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
鞍山市| 勃利县| 兴国县| 漳浦县| 长寿区| 大关县| 平江县| 陇南市| 田林县| 海盐县| 无锡市| 定远县| 凤翔县| 浠水县| 邯郸市| 定兴县| 沾益县| 分宜县| 中宁县| 松溪县| 平武县| 隆化县| 荥阳市| 疏勒县| 通化县| 兰溪市| 杂多县| 临湘市| 新龙县| 延川县| 弥渡县| 类乌齐县| 左云县| 台州市| 句容市| 沂水县| 泰和县| 海门市| 白河县| 团风县| 陵川县|