C语言编写一个程序 采用顺序表 存储一元多项式,并实现两个多项式相加运算,要求: (1)创建存储多项式的有序表(按无序输入)ha和 hb;(2)求ha和hb相加产生多项式hc。(3)输出多项式ha、hb和hc;
时间: 2024-11-29 19:37:06 浏览: 51
在C语言中,我们可以使用结构体来表示多项式的系数和次数,然后通过顺序表(数组)来存储多项式。以下是一个简单的实现示例:
```c
#include <stdio.h>
// 定义多项式的项结构
typedef struct {
int coefficient; // 系数
int exponent; // 次数
} PolynomialTerm;
// 定义多项式类型的指针
typedef PolynomialTerm* Polynomial;
// 功能:添加两个多项式的项
void add_terms(Polynomial ha, Polynomial hb, Polynomial hc) {
for (int i = 0; i < 10 && ha[i].exponent != -1; i++) { // 假设每个多项式最多有10项
PolynomialTerm term_ha = ha[i];
PolynomialTerm term_hb = (hb + i < 10) ? hb[i] : {0, -1}; // 如果hb不存在这个位置,则默认系数为0
if (term_ha.exponent == term_hb.exponent) {
hc[i].coefficient += term_ha.coefficient + term_hb.coefficient;
} else if (term_ha.exponent > term_hb.exponent) {
hc[i].coefficient += term_ha.coefficient;
if (i < 9) {
hc[i+1].coefficient += term_hb.coefficient;
}
} else {
if (i < 9) {
hc[i].coefficient += term_hb.coefficient;
}
}
}
// 清除多余的0项
while (hc-1) {
hc++;
}
}
// 主函数
int main() {
Polynomial ha = (Polynomial)malloc(sizeof(PolynomialTerm) * 10);
Polynomial hb = (Polynomial)malloc(sizeof(PolynomialTerm) * 10);
Polynomial hc = (Polynomial)malloc(sizeof(PolynomialTerm) * 10);
// 输入多项式ha
printf("Enter coefficients and exponents of polynomial ha (separated by space): ");
for (int i = 0; i < 10; i++) {
scanf("%d %d", &ha[i].coefficient, &ha[i].exponent);
if (ha[i].exponent == -1) break; // 表示输入结束
}
// 输入多项式hb
printf("\nEnter coefficients and exponents of polynomial hb (separated by space): ");
for (int i = 0; i < 10; i++) {
scanf("%d %d", &hb[i].coefficient, &hb[i].exponent);
if (hb[i].exponent == -1) break;
}
// 相加
add_terms(ha, hb, hc);
// 输出结果
printf("Polynomial ha: ");
for (int i = 0; i < 10; i++) {
if (hc[i].exponent != -1) {
printf("%dx^%d ", hc[i].coefficient, hc[i].exponent);
}
}
printf("\n");
printf("Polynomial hb: ");
for (int i = 0; i < 10; i++) {
if (hb[i].exponent != -1) {
printf("%dx^%d ", hb[i].coefficient, hb[i].exponent);
}
}
printf("\n");
printf("Sum (polynomial hc): ");
for (int i = 0; i < 10; i++) {
if (hc[i].exponent != -1) {
printf("%dx^%d ", hc[i].coefficient, hc[i].exponent);
}
}
printf("\n");
free(ha);
free(hb);
free(hc);
return 0;
}
```
在这个程序中,我们首先创建了三个多项式变量`ha`、`hb`和`hc`,然后通过用户输入读取系数和指数,接着计算它们的和并存储在`hc`中。最后,输出三个多项式的内容。
阅读全文