C语言实现一元多项式的乘法
时间: 2023-06-02 15:01:57 浏览: 91
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int coef; // 系数
int exp; // 指数
struct node *next;
} Polynomial;
// 创建多项式
Polynomial *create() {
Polynomial *head = (Polynomial *)malloc(sizeof(Polynomial));
head->next = NULL;
Polynomial *p = head;
int n;
printf("请输入多项式的项数:");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
Polynomial *q = (Polynomial *)malloc(sizeof(Polynomial));
printf("请输入第%d项的系数和指数:", i);
scanf("%d%d", &q->coef, &q->exp);
p->next = q;
p = q;
}
p->next = NULL;
return head;
}
// 打印多项式
void print(Polynomial *head) {
Polynomial *p = head->next;
while (p) {
printf("%dx^%d", p->coef, p->exp);
p = p->next;
if (p) {
printf("+");
}
}
printf("\n");
}
// 多项式乘法
Polynomial *multiply(Polynomial *head1, Polynomial *head2) {
Polynomial *head = (Polynomial *)malloc(sizeof(Polynomial));
head->next = NULL;
Polynomial *p = head1->next;
while (p) {
Polynomial *q = head2->next;
while (q) {
Polynomial *r = (Polynomial *)malloc(sizeof(Polynomial));
r->coef = p->coef * q->coef;
r->exp = p->exp + q->exp;
r->next = head->next;
head->next = r;
q = q->next;
}
p = p->next;
}
return head;
}
int main() {
Polynomial *head1 = create();
Polynomial *head2 = create();
printf("多项式1:");
print(head1);
printf("多项式2:");
print(head2);
Polynomial *head = multiply(head1, head2);
printf("多项式1乘以多项式2:");
print(head);
return 0;
}
```
阅读全文