C语言,一元多项式相加,链式结构
时间: 2024-10-18 21:18:25 浏览: 24
C语言一元多项式简单计算
3星 · 编辑精心推荐
在C语言中,一元多项式通常通过链表结构来表示,每个节点包含系数和变量指数,可以方便地实现相加操作。下面是一个简单的示例,展示了如何使用链表结构表示一元多项式以及它们之间的相加:
首先,定义一个链表节点的结构体:
```c
typedef struct PolynomialTerm {
float coefficient; // 系数
int exponent; // 指数
struct PolynomialTerm* next; // 指向下一个项的指针
} PolynomialTerm;
```
接着,创建一个函数来创建一个新的链表节点:
```c
PolynomialTerm* createTerm(float coef, int exp) {
PolynomialTerm* term = (PolynomialTerm*)malloc(sizeof(PolynomialTerm));
term->coefficient = coef;
term->exponent = exp;
term->next = NULL;
return term;
}
```
然后,定义一个函数来进行两个多项式的相加:
```c
void addTerms(PolynomialTerm** result, PolynomialTerm* a, PolynomialTerm* b) {
PolynomialTerm* current_a = a, *current_b = b, *new_head = NULL;
while (a && b) {
PolynomialTerm* new_term = createTerm(current_a->coefficient + current_b->coefficient, max(current_a->exponent, current_b->exponent));
if (!new_head) {
new_head = new_term;
} else {
current_result->next = new_term;
}
current_a = current_a->next;
current_b = current_b->next;
}
// 处理剩余项(如果存在)
while (current_a) {
PolynomialTerm* new_term = createTerm(current_a->coefficient, current_a->exponent);
if (!new_head) {
new_head = new_term;
} else {
current_result->next = new_term;
}
current_a = current_a->next;
}
while (current_b) {
PolynomialTerm* new_term = createTerm(current_b->coefficient, current_b->exponent);
if (!new_head) {
new_head = new_term;
} else {
current_result->next = new_term;
}
current_b = current_b->next;
}
*result = new_head;
}
```
最后,在主函数中使用上述函数:
```c
int main() {
PolynomialTerm* poly1 = createTerm(2.0f, 2); // 2x^2
PolynomialTerm* poly2 = createTerm(-1.0f, 1); // -x
PolynomialTerm* result = NULL;
addTerms(&result, poly1, poly2);
// 打印结果多项式
PolynomialTerm* temp = result;
while (temp) {
printf("%.1fx^%d -> ", temp->coefficient, temp->exponent);
temp = temp->next;
}
printf("\n");
return 0;
}
```
阅读全文