用c语言写一段代码一元稀疏多项式计算器
时间: 2023-08-13 07:08:23 浏览: 189
C语言-一元稀疏多项式计算器
好的,下面是一元稀疏多项式计算器的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义结构体表示多项式中的一个项
typedef struct Node {
float coef; // 系数
int exp; // 指数
struct Node* next; // 指向下一个项的指针
} Node;
// 定义结构体表示多项式
typedef struct {
Node* head; // 链表头指针
int degree; // 最高次数
} Poly;
// 初始化一个空的多项式
void initPoly(Poly* p) {
p->head = NULL;
p->degree = 0;
}
// 在多项式中插入一个项
void insert(Node** head, float coef, int exp) {
Node* prev = NULL;
Node* curr = *head;
// 找到插入位置
while (curr != NULL && curr->exp > exp) {
prev = curr;
curr = curr->next;
}
// 如果已经存在相同指数的项,则相加系数
if (curr != NULL && curr->exp == exp) {
curr->coef += coef;
} else {
// 否则新建一个项并插入链表
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->coef = coef;
new_node->exp = exp;
new_node->next = curr;
if (prev == NULL) {
*head = new_node;
} else {
prev->next = new_node;
}
}
}
// 从标准输入读取一个多项式
void readPoly(Poly* p) {
int n;
float coef;
int exp;
printf("请输入项的个数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第%d个项的系数和指数:", i + 1);
scanf("%f%d", &coef, &exp);
insert(&p->head, coef, exp);
}
// 计算最高次数
if (p->head != NULL) {
p->degree = p->head->exp;
}
}
// 打印一个多项式
void printPoly(Poly* p) {
Node* curr = p->head;
while (curr != NULL) {
printf("%.2fx^%d", curr->coef, curr->exp);
if (curr->next != NULL) {
printf(" + ");
}
curr = curr->next;
}
printf("\n");
}
// 计算两个多项式的和
Poly addPoly(Poly* p1, Poly* p2) {
Poly result;
initPoly(&result);
Node* curr1 = p1->head;
Node* curr2 = p2->head;
while (curr1 != NULL && curr2 != NULL) {
if (curr1->exp > curr2->exp) {
insert(&result.head, curr1->coef, curr1->exp);
curr1 = curr1->next;
} else if (curr1->exp < curr2->exp) {
insert(&result.head, curr2->coef, curr2->exp);
curr2 = curr2->next;
} else {
insert(&result.head, curr1->coef + curr2->coef, curr1->exp);
curr1 = curr1->next;
curr2 = curr2->next;
}
}
// 处理剩余的项
while (curr1 != NULL) {
insert(&result.head, curr1->coef, curr1->exp);
curr1 = curr1->next;
}
while (curr2 != NULL) {
insert(&result.head, curr2->coef, curr2->exp);
curr2 = curr2->next;
}
// 计算最高次数
if (result.head != NULL) {
result.degree = result.head->exp;
}
return result;
}
int main() {
Poly p1, p2, sum;
initPoly(&p1);
initPoly(&p2);
initPoly(&sum);
printf("请输入第一个多项式:\n");
readPoly(&p1);
printf("第一个多项式为:");
printPoly(&p1);
printf("请输入第二个多项式:\n");
readPoly(&p2);
printf("第二个多项式为:");
printPoly(&p2);
sum = addPoly(&p1, &p2);
printf("两个多项式的和为:");
printPoly(&sum);
return 0;
}
```
这段代码实现了一元稀疏多项式的输入、输出和加法运算。你可以根据需要进行修改和扩展。
阅读全文