用C语言写出多项式的乘法
时间: 2023-10-05 17:09:59 浏览: 89
以下是用C语言实现多项式乘法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_TERM 100
typedef struct {
float coef; // 系数
int exp; // 指数
} Term;
void multiply(Term poly1[], int n1, Term poly2[], int n2, Term result[], int *n3);
void display(Term poly[], int n);
int main() {
Term poly1[MAX_TERM], poly2[MAX_TERM], result[MAX_TERM];
int n1, n2, n3;
// 输入第一个多项式
printf("Enter the number of terms in polynomial 1: ");
scanf("%d", &n1);
printf("Enter the terms of polynomial 1:\n");
for (int i = 0; i < n1; i++) {
printf("Term %d: ", i + 1);
scanf("%f %d", &poly1[i].coef, &poly1[i].exp);
}
// 输入第二个多项式
printf("\nEnter the number of terms in polynomial 2: ");
scanf("%d", &n2);
printf("Enter the terms of polynomial 2:\n");
for (int i = 0; i < n2; i++) {
printf("Term %d: ", i + 1);
scanf("%f %d", &poly2[i].coef, &poly2[i].exp);
}
// 计算结果多项式
multiply(poly1, n1, poly2, n2, result, &n3);
// 输出结果多项式
printf("\nResultant polynomial:\n");
display(result, n3);
return 0;
}
// 多项式相乘
void multiply(Term poly1[], int n1, Term poly2[], int n2, Term result[], int *n3) {
// 初始化结果多项式
for (int i = 0; i < MAX_TERM; i++) {
result[i].coef = 0.0;
result[i].exp = 0;
}
*n3 = 0;
// 计算结果多项式
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
int exp = poly1[i].exp + poly2[j].exp;
float coef = poly1[i].coef * poly2[j].coef;
int k;
for (k = 0; k < *n3; k++) {
if (exp == result[k].exp) {
result[k].coef += coef;
break;
}
}
if (k == *n3) {
result[*n3].coef = coef;
result[*n3].exp = exp;
(*n3)++;
}
}
}
}
// 输出多项式
void display(Term poly[], int n) {
for (int i = 0; i < n; i++) {
if (poly[i].coef >= 0.0 && i != 0) {
printf("+ ");
}
printf("%.2f", poly[i].coef);
if (poly[i].exp == 1) {
printf("x ");
} else if (poly[i].exp != 0) {
printf("x^%d ", poly[i].exp);
}
}
printf("\n");
}
```
该程序定义了一个 `Term` 结构体来表示一个多项式中的一项,其中包含系数和指数两个成员变量。`multiply` 函数用于计算两个多项式的乘积,并将结果存储在 `result` 数组中。`display` 函数用于将一个多项式输出到控制台上。
在程序运行时,用户需要输入两个多项式的系数和指数,程序将计算它们的乘积,并将结果输出到控制台上。