用c语言建立一元稀疏多项式简单计算器:(1) 输入并建立多项式;(2) 输出多项式,输出形式为整数序列:n,c1,e1, c2,e2, cn,en,其中n是多项式的项数,ci,ei,分别是第i项的系数和指数,序列按指数降序排序;(3) 多项式a和b相加,建立多项式a+b
时间: 2024-11-09 08:30:44 浏览: 15
在C语言中,你可以使用结构体来表示多项式的每一项,数组来存储所有项,并实现输入、输出和相加的功能。以下是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式项的数据结构
typedef struct {
int coefficient; // 系数
int exponent; // 指数
} Term;
// 用于比较指数的辅助函数
int compare_exponents(const void *a, const void *b) {
const Term *termA = a;
const Term *termB = b;
return termB- termA->exponent;
}
// 创建新项并添加到多项式
Term* add_term(Term *polynomial, int coefficient, int exponent) {
Term *new_term = (Term*)malloc(sizeof(Term));
new_term->coefficient = coefficient;
new_term->exponent = exponent;
if (!polynomial) {
polynomial = new_term;
} else {
// 按照指数降序排列
qsort(polynomial, sizeof(Term), sizeof(Term), compare_exponents);
for (size_t i = 0; i < sizeof(polynomial)/sizeof(Term); ++i) {
if (polynomial[i].exponent < exponent) {
polynomial = realloc(polynomial, (i+2)*sizeof(Term));
polynomial[i] = *new_term;
break;
}
}
if (polynomial[i].exponent == exponent) {
polynomial[i].coefficient += coefficient;
} else {
polynomial[i+1] = *new_term;
}
}
return polynomial;
}
// 打印多项式
void print_polynomial(Term *polynomial) {
printf("n=%d: ", sizeof(polynomial)/sizeof(Term));
for (size_t i = 0; i < sizeof(polynomial)/sizeof(Term); ++i) {
printf("%d,%d, ", polynomial[i].coefficient, polynomial[i].exponent);
}
printf("\n");
}
int main() {
Term *polynomial1 = NULL, *polynomial2 = NULL, *sum = NULL;
int input1, input2, coefficient, exponent;
// 输入并构建多项式
while (scanf("%d,%d", &input1, &input2) == 2 && input1 != 0) {
add_term(&polynomial1, input1, input2);
}
// 对第二个多项式做同样的操作
scanf("%d,%d", &input1, &input2);
add_term(&polynomial2, input1, input2);
// 相加两个多项式
sum = add_term(NULL, 0, 0);
for (size_t i = 0; i < sizeof(polynomial1)/sizeof(Term); ++i) {
sum = add_term(sum, polynomial1[i].coefficient, polynomial1[i].exponent);
}
for (size_t i = 0; i < sizeof(polynomial2)/sizeof(Term); ++i) {
sum = add_term(sum, polynomial2[i].coefficient, polynomial2[i].exponent);
}
// 输出结果多项式
print_polynomial(sum);
free(polynomial1);
free(polynomial2);
free(sum);
return 0;
}
```
阅读全文