多项式乘法的实现c语言代码
时间: 2023-10-05 11:10:13 浏览: 62
以下是一个简单的多项式乘法的实现C语言代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
struct Poly {
int coef[MAX_SIZE]; // 多项式系数
int expn[MAX_SIZE]; // 多项式指数
int len; // 多项式长度
};
void InitPoly(struct Poly *p) {
for (int i = 0; i < MAX_SIZE; i++) {
p->coef[i] = 0;
p->expn[i] = 0;
}
p->len = 0;
}
void PrintPoly(struct Poly *p) {
for (int i = 0; i < p->len; i++) {
printf("%dx^%d ", p->coef[i], p->expn[i]);
if (i < p->len - 1) {
printf("+ ");
}
}
printf("\n");
}
void MulPoly(struct Poly *p1, struct Poly *p2, struct Poly *result) {
InitPoly(result);
for (int i = 0; i < p1->len; i++) {
for (int j = 0; j < p2->len; j++) {
int coef = p1->coef[i] * p2->coef[j];
int expn = p1->expn[i] + p2->expn[j];
int k;
for (k = 0; k < result->len; k++) {
if (expn == result->expn[k]) {
result->coef[k] += coef;
break;
}
}
if (k == result->len) {
result->coef[k] = coef;
result->expn[k] = expn;
result->len++;
}
}
}
}
int main() {
struct Poly p1 = {{1, 2, 3}, {2, 1, 0}, 3};
struct Poly p2 = {{4, 5, 6}, {3, 2, 1}, 3};
struct Poly result;
InitPoly(&result);
MulPoly(&p1, &p2, &result);
PrintPoly(&p1);
printf("* ");
PrintPoly(&p2);
printf("= ");
PrintPoly(&result);
return 0;
}
```
这个代码定义了一个 `Poly` 结构体来表示多项式,包含多项式系数、指数和长度。`InitPoly` 函数用于初始化多项式,`PrintPoly` 函数用于打印多项式,`MulPoly` 函数用于计算两个多项式的乘积并存储到一个新的多项式中。
在 `main` 函数中定义了两个多项式 `p1` 和 `p2`,并调用 `MulPoly` 函数计算它们的乘积,最后调用 `PrintPoly` 函数打印结果多项式。