编写程序实现一元多项式的创建以及两个一元多项式相加和相乘的操作C语言
时间: 2024-12-23 19:15:45 浏览: 2
一元多项式的相乘(C链表实现).
在C语言中,我们可以创建一个结构体表示一元多项式,包含系数数组和次数信息。以下是基本的实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义多项式结构体
typedef struct {
int degree; // 次数
double coefficients[100]; // 系数数组,假设最多有100项
} Polynomial;
// 创建多项式函数
Polynomial* create_polynomial(int degree) {
Polynomial* poly = (Polynomial*)malloc(sizeof(Polynomial));
poly->degree = degree;
for (int i = 0; i <= degree; i++) {
if (i == 0)
poly->coefficients[i] = 0;
else
poly->coefficients[i] = 0.0;
}
return poly;
}
// 添加两个多项式
void add_polynomials(Polynomial* poly1, Polynomial* poly2, Polynomial** result) {
*result = create_polynomial(max(poly1->degree, poly2->degree));
for (int i = 0; i <= (*result)->degree; i++) {
(*result)->coefficients[i] += poly1->coefficients[i] + poly2->coefficients[i];
}
}
// 乘法操作,这里仅展示思路,实际需要递归或使用循环
void multiply_polynomials(Polynomial* poly1, Polynomial* poly2, Polynomial** result) {
*result = create_polynomial(poly1->degree + poly2->degree);
for (int i = 0; i <= *result->degree; i++) {
double term = 0;
for (int j = 0; j <= i; j++) {
term += poly1->coefficients[j] * poly2->coefficients[i - j];
}
(*result)->coefficients[i] = term;
}
}
// 打印多项式
void print_polynomial(Polynomial* poly) {
printf("Polynomial with degree %d:\n", poly->degree);
for (int i = 0; i <= poly->degree; i++) {
printf("%.2lfx^%d + ", poly->coefficients[i], i);
}
printf("\n");
}
int main() {
Polynomial* poly1 = create_polynomial(3); // 示例多项式1: ax^3 + bx^2 + c
Polynomial* poly2 = create_polynomial(2); // 示例多项式2: dx^2 + ex
// 初始化并设置系数
poly1->coefficients[0] = 2.0;
poly1->coefficients[1] = 3.0;
poly1->coefficients[2] = 4.0;
poly2->coefficients[0] = 5.0;
poly2->coefficients[1] = 6.0;
Polynomial* sum_poly = NULL;
add_polynomials(poly1, poly2, &sum_poly);
print_polynomial(sum_poly);
Polynomial* product_poly = NULL;
multiply_polynomials(poly1, poly2, &product_poly);
print_polynomial(product_poly);
free(sum_poly);
free(product_poly);
return 0;
}
```
在这个例子中,我们首先创建了表示多项式的结构体,并实现了创建、添加和乘法的基本操作。注意,这个乘法函数是一个简化版,实际计算过程中可能需要用到更复杂的算法,如分治法或动态规划。
阅读全文