用C语言实现一元多项式加减法与乘法完整代码
时间: 2024-10-21 18:06:05 浏览: 35
顺序结构、动态链表结构下的一元多项式的加法、减法、乘法的实现。.docx
5星 · 资源好评率100%
在C语言中,可以使用结构体和指针来实现一元多项式的加减法与乘法。这里是一个简化的例子,我们首先定义一个结构体`Polynomial`表示一个多项式项:
```c
#include <stdio.h>
typedef struct {
double coefficient; // 系数
int exponent; // 指数
} Term;
// 单个项的加法
Term addTerms(Term a, Term b) {
if (a.exponent == b.exponent)
return (Term){a.coefficient + b.coefficient, a.exponent};
else if (a.exponent > b.exponent)
return a;
else
return b;
}
// 单个项的减法
Term subtractTerms(Term a, Term b) {
if (a.exponent == b.exponent)
return (Term){a.coefficient - b.coefficient, a.exponent};
else if (a.exponent > b.exponent)
return a;
else
return (Term){b.coefficient, b.exponent};
}
// 两个多项式的加法
void addPolynomials(Term* result, Term* poly1, Term* poly2, int size1, int size2) {
for (int i = 0; i < size1; ++i) {
*result++ = addTerms(poly1[i], (size2 <= i) ? poly2[i] : (Term){0, 0});
}
while (size2--) {
*result++ = poly2[size2];
}
}
// 两个多项式的减法
void subtractPolynomials(Term* result, Term* poly1, Term* poly2, int size1, int size2) {
for (int i = 0; i < size1 && i < size2; ++i) {
*result++ = subtractTerms(poly1[i], poly2[i]);
}
for (int i = size1; i < size2; ++i) {
*result++ = poly2[i];
}
}
// 两个多项式的乘法(笛卡尔积)
void multiplyPolynomials(Term** result, Term* poly1, Term* poly2, int size1, int size2) {
int newSize = size1 + size2 - 1;
Term* tempResult = malloc(newSize * sizeof(Term));
for (int i = 0; i < size1; ++i) {
for (int j = 0; j < size2; ++j) {
Term product = {poly1[i].coefficient * poly2[j].coefficient,
poly1[i].exponent + poly2[j].exponent};
tempResult[newSize - 1 - (i + j)] = product;
}
}
*result = tempResult;
}
int main() {
Term poly1[] = {{2, 1}, {1, 2}, {0, 3}};
Term poly2[] = {{3, 0}, {-1, 1}};
int size1 = sizeof(poly1) / sizeof(poly1[0]);
int size2 = sizeof(poly2) / sizeof(poly2[0]);
Term* sum = malloc(size1 + size2 * sizeof(Term)); // 加法结果预留空间
addPolynomials(sum, poly1, poly2, size1, size2);
printf("Sum: ");
for (int i = 0; i < size1 + size2; ++i) {
printf("%.2f*x^%d ", sum[i].coefficient, sum[i].exponent);
}
printf("\n");
Term* diff = malloc(size1 + size2 * sizeof(Term)); // 减法结果预留空间
subtractPolynomials(diff, poly1, poly2, size1, size2);
printf("Difference: ");
for (int i = 0; i < size1 + size2; ++i) {
printf("%.2f*x^%d ", diff[i].coefficient, diff[i].exponent);
}
printf("\n");
Term** prod = malloc(size1 * size2 * sizeof(Term*)); // 乘法结果需要动态分配数组
multiplyPolynomials(prod, poly1, poly2, size1, size2);
printf("Product: ");
for (int i = 0; i < newSize; ++i) {
printf("%.2f*x^%d ", prod[i]->coefficient, prod[i]->exponent);
}
printf("\n");
free(sum);
free(diff);
if (prod != NULL) {
free(*prod);
free(prod);
}
return 0;
}
```
这段代码实现了多项式的一维数组形式,并完成了基本的加、减、乘操作。注意,乘法的结果需要额外的空间存储,所以返回的是指向新生成多项式的指针。
阅读全文