用c语言编写一个程序,采用顺序表存储一元多项式,并实现两个多项式相加运算,要求: (1)创建存储多项式的有序表(按无序输入)ha和hb; (2)求ha和hb相加产生多项式hc。 (3)输出多项式ha、hb和hc;
时间: 2024-11-20 17:40:34 浏览: 19
下面是一个简单的C语言程序,用于创建顺序表存储一元多项式并实现两个多项式的相加操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式的结构体
typedef struct {
int degree;
double* coefficients; // 存储多项式的系数
} Polynomial;
// 动态分配空间并初始化多项式
Polynomial* create_polynomial(int degree) {
Polynomial* poly = (Polynomial*)malloc(sizeof(Polynomial));
poly->degree = degree;
poly->coefficients = malloc(degree * sizeof(double));
for (int i = 0; i <= degree; ++i) {
poly->coefficients[i] = 0;
}
return poly;
}
// 输入多项式系数
void input_polynomial(Polynomial* poly, const char* name) {
printf("Enter the %s polynomial coefficients (separated by space): ", name);
int deg;
scanf("%d", °);
poly->degree = deg;
for (int i = 0; i <= deg; ++i) {
scanf("%lf", &poly->coefficients[i]);
}
}
// 两个多项式相加
Polynomial* add_polynomials(Polynomial* ha, Polynomial* hb) {
Polynomial* hc = create_polynomial(ha->degree + hb->degree);
for (int i = 0; i <= ha->degree; ++i) {
hc->coefficients[i] += ha->coefficients[i];
}
for (int i = 0; i <= hb->degree; ++i) {
if (i <= ha->degree) { // 避免重复添加同一次幂
continue;
}
hc->coefficients[i] += hb->coefficients[i];
}
return hc;
}
// 输出多项式
void print_polynomial(const Polynomial* poly) {
printf("The %s polynomial is:\n", "HC"); // 使用HC代替实际的多项式名称
for (int i = 0; i <= poly->degree; ++i) {
printf("%dx^%d + ", poly->coefficients[i], i);
}
printf("\n");
}
int main() {
Polynomial* ha = create_polynomial(0);
Polynomial* hb = create_polynomial(0);
input_polynomial(ha, "ha");
input_polynomial(hb, "hb");
Polynomial* hc = add_polynomials(ha, hb);
print_polynomial(ha); // 输出ha
print_polynomial(hb); // 输出hb
print_polynomial(hc); // 输出hc
free(ha->coefficients);
free(ha);
free(hb->coefficients);
free(hb);
return 0;
}
```
这个程序首先定义了多项式结构,然后实现了创建、输入、相加和输出多项式的功能。注意,输入的部分需要用户手动输入系数,可以根据需求修改为读取文件或其他方式。
阅读全文