用C语言写多项式相加减
时间: 2024-09-14 14:08:16 浏览: 42
在C语言中,我们可以使用数组来存储多项式的系数及其对应的变量次数,然后编写函数来进行多项式的加法和减法操作。这里提供一个简单的示例,仅支持一次、二次和常数项的加减运算:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Polynomial {
double* coefficients; // 数组存储系数
int degree; // 最高次幂
} Polynomial;
// 添加两个多项式
Polynomial add_poly(Polynomial poly1, Polynomial poly2) {
if (poly1.degree != poly2.degree) {
printf("两项多项式的度数不匹配,无法相加。\n");
return poly1;
}
Polynomial result;
result.degrees = poly1.degree + 1;
result.coefficients = malloc(sizeof(double) * result.degrees);
for (int i = 0; i <= poly1.degree; ++i) {
result.coefficients[i] = poly1.coefficients[i] + poly2.coefficients[i];
}
return result;
}
// 减去两个多项式
Polynomial subtract_poly(Polynomial poly1, Polynomial poly2) {
if (poly1.degree != poly2.degree) {
printf("两项多项式的度数不匹配,无法相减。\n");
return poly1;
}
Polynomial result;
result.degrees = poly1.degree + 1;
result.coefficients = malloc(sizeof(double) * result.degrees);
for (int i = 0; i <= poly1.degree; ++i) {
result.coefficients[i] = poly1.coefficients[i] - poly2.coefficients[i];
}
return result;
}
// 示例
void print_polynomial(Polynomial poly) {
printf("多项式:");
for (int i = poly.degree; i >= 0; --i) {
printf("%.2f*x^%d + ", poly.coefficients[i], i);
}
printf("%.2fx^0\n", poly.coefficients[0]);
}
int main() {
Polynomial p1 = { {1.5, 2.0}, 2 };
Polynomial p2 = { {2.0, 1.0}, 2 };
Polynomial sum = add_poly(p1, p2);
Polynomial diff = subtract_poly(p1, p2);
print_polynomial(sum);
print_polynomial(diff);
free(sum.coefficients);
free(diff.coefficients);
return 0;
}
```
这个代码首先定义了一个结构体`Polynomial`来存储多项式的系数和最高次幂。`add_poly`和`subtract_poly`函数分别实现了两个多项式的加法和减法。注意,这里的实现假设输入的多项式都是有公共的最高次幂,如果没有,需要额外检查。
阅读全文