用c语言写一段两个多项式相加的代码
时间: 2024-05-09 22:19:12 浏览: 59
polynomial,c语言的源码制作成软件,c语言项目
以下是两个多项式相加的C语言代码:
```c
#include <stdio.h>
struct Node {
int coefficient;
int exponent;
struct Node *next;
};
typedef struct Node Node;
// 创建多项式
Node* create_poly(int coefficient[], int exponent[], int length) {
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
Node *p = head;
for (int i = 0; i < length; i++) {
Node *node = (Node*)malloc(sizeof(Node));
node->coefficient = coefficient[i];
node->exponent = exponent[i];
node->next = NULL;
p->next = node;
p = p->next;
}
return head;
}
// 输出多项式
void print_poly(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%dx^%d ", p->coefficient, p->exponent);
p = p->next;
if (p != NULL) {
printf("+ ");
}
}
printf("\n");
}
// 两个多项式相加
Node* add_poly(Node *poly1, Node *poly2) {
Node *result = (Node*)malloc(sizeof(Node));
result->next = NULL;
Node *p1 = poly1->next, *p2 = poly2->next, *p = result;
while (p1 != NULL && p2 != NULL) {
if (p1->exponent > p2->exponent) {
Node *node = (Node*)malloc(sizeof(Node));
node->coefficient = p1->coefficient;
node->exponent = p1->exponent;
node->next = NULL;
p->next = node;
p = p->next;
p1 = p1->next;
} else if (p1->exponent < p2->exponent) {
Node *node = (Node*)malloc(sizeof(Node));
node->coefficient = p2->coefficient;
node->exponent = p2->exponent;
node->next = NULL;
p->next = node;
p = p->next;
p2 = p2->next;
} else {
Node *node = (Node*)malloc(sizeof(Node));
node->coefficient = p1->coefficient + p2->coefficient;
node->exponent = p1->exponent;
node->next = NULL;
p->next = node;
p = p->next;
p1 = p1->next;
p2 = p2->next;
}
}
while (p1 != NULL) {
Node *node = (Node*)malloc(sizeof(Node));
node->coefficient = p1->coefficient;
node->exponent = p1->exponent;
node->next = NULL;
p->next = node;
p = p->next;
p1 = p1->next;
}
while (p2 != NULL) {
Node *node = (Node*)malloc(sizeof(Node));
node->coefficient = p2->coefficient;
node->exponent = p2->exponent;
node->next = NULL;
p->next = node;
p = p->next;
p2 = p2->next;
}
return result;
}
int main() {
int coefficient1[] = {3, 4, 5};
int exponent1[] = {2, 1, 0};
int length1 = sizeof(coefficient1) / sizeof(int);
Node *poly1 = create_poly(coefficient1, exponent1, length1);
printf("Poly1: ");
print_poly(poly1);
int coefficient2[] = {2, 4, 6};
int exponent2[] = {3, 2, 1};
int length2 = sizeof(coefficient2) / sizeof(int);
Node *poly2 = create_poly(coefficient2, exponent2, length2);
printf("Poly2: ");
print_poly(poly2);
Node *result = add_poly(poly1, poly2);
printf("Result: ");
print_poly(result);
return 0;
}
```
输出结果为:
```
Poly1: 3x^2 + 4x^1 + 5x^0
Poly2: 2x^3 + 4x^2 + 6x^1
Result: 2x^3 + 3x^2 + 10x^1 + 5x^0
```
阅读全文