c语言 求两个多项式的乘积(1)编写函数实现一个多项式的输入,返回多项式链表的头指针。(2)编写函数实现两个多项式相乘,返回结果多项式链表的头指针。(3)编写函数输出一个多项式的二元组序列。(4)在main函数中分别调用上述函数,实现输入两个多项式,先输入多项式非零项的个数,再输入每一对非零项系数和指数。输出乘积的系数和指数。
时间: 2024-02-22 12:58:17 浏览: 58
c语言实现多项式乘法
5星 · 资源好评率100%
好的,我来为你解答。
首先,我们需要定义一个多项式的结构体,包含系数和指数两个成员:
```c
typedef struct polyNode{
int coef; // 系数
int expon; // 指数
struct polyNode *next; // 指向下一个节点的指针
} PolyNode, *Polynomial;
```
接下来,我们就可以编写题目要求的函数了。
1. 实现多项式的输入
```c
Polynomial createPoly() {
Polynomial head = (Polynomial)malloc(sizeof(PolyNode));
head->next = NULL;
PolyNode *tail = head;
int n, coef, expon;
printf("请输入多项式非零项的个数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第%d项的系数和指数:", i+1);
scanf("%d%d", &coef, &expon);
PolyNode *p = (PolyNode*)malloc(sizeof(PolyNode));
p->coef = coef;
p->expon = expon;
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
```
2. 实现两个多项式的相乘
```c
Polynomial polyMultiply(Polynomial p1, Polynomial p2) {
Polynomial head = (Polynomial)malloc(sizeof(PolyNode));
head->next = NULL;
PolyNode *tail = head;
for (PolyNode *t1 = p1->next; t1 != NULL; t1 = t1->next) {
for (PolyNode *t2 = p2->next; t2 != NULL; t2 = t2->next) {
int coef = t1->coef * t2->coef;
int expon = t1->expon + t2->expon;
PolyNode *p = (PolyNode*)malloc(sizeof(PolyNode));
p->coef = coef;
p->expon = expon;
p->next = NULL;
// 将新节点插入到结果多项式中
// 如果指数相同,则合并同类项
for (PolyNode *t = head->next; t != NULL; t = t->next) {
if (t->expon == expon) {
t->coef += coef;
break;
} else if (t->next == NULL || t->next->expon < expon) {
p->next = t->next;
t->next = p;
break;
}
}
}
}
return head;
}
```
3. 实现多项式的输出
```c
void printPoly(Polynomial p) {
for (PolyNode *t = p->next; t != NULL; t = t->next) {
printf("(%d,%d)", t->coef, t->expon);
if (t->next != NULL) printf(" -> ");
}
printf("\n");
}
```
最后,在主函数中调用上述函数即可:
```c
int main() {
Polynomial p1, p2, result;
printf("请输入第一个多项式:\n");
p1 = createPoly();
printf("请输入第二个多项式:\n");
p2 = createPoly();
result = polyMultiply(p1, p2);
printf("乘积的系数和指数:");
printPoly(result);
return 0;
}
```
以上就是完整的代码实现。
阅读全文