多项式输入c语言代码
时间: 2024-10-08 08:23:51 浏览: 35
在C语言中,处理多项式的常见操作包括加法、减法、乘法以及计算值。下面是一个简单的多项式表示结构体的例子,用于存储系数和次数:
```c
#include <stdio.h>
// 定义多项式结构体
typedef struct {
int degree; // 次数
double coefficients[100]; // 最高次项系数数组,假设最多有99项
} Polynomial;
// 初始化多项式
void init_polynomial(Polynomial* poly, int n) {
poly->degree = n - 1;
for (int i = 0; i <= n; ++i)
poly->coefficients[i] = 0.0; // 初始化所有系数为0
}
// 添加两个多项式
void add_polynomials(Polynomial* result, const Polynomial& poly1, const Polynomial& poly2) {
int max_degree = MAX(poly1.degree, poly2.degree);
for (int i = 0; i <= max_degree; ++i) {
result->coefficients[i] += poly1.coefficients[i] + poly2.coefficients[i];
}
result->degree = max_degree;
}
// 计算多项式值
double evaluate_polynomial(const Polynomial& poly, double x) {
int n = poly.degree;
double term = poly.coefficients[n] * pow(x, n);
double sum = term;
for (n--; n >= 0; --n) {
term = poly.coefficients[n] * pow(x, n);
sum += term;
}
return sum;
}
// 示例:主函数演示多项式操作
int main() {
Polynomial p1, p2, result;
init_polynomial(&p1, 2); // p1 = a + bx
init_polynomial(&p2, 2); // p2 = c + dx
p1.coefficients[0] = 1; // a
p1.coefficients[1] = 2; // b
p2.coefficients[0] = 3; // c
p2.coefficients[1] = 4; // d
// 打印多项式
printf("p1(x) = %.2fx^%d + %.2f\n", p1.coefficients[0], p1.degree, p1.coefficients[1]);
printf("p2(x) = %.2fx^%d + %.2f\n", p2.coefficients[0], p2.degree, p2.coefficients[1]);
// 添加多项式
add_polynomials(&result, p1, p2);
printf("p1(x) + p2(x) = %.2fx^%d + %.2f\n", result.coefficients[0], result.degree, result.coefficients[1]);
// 计算多项式值
double x = 5.0;
printf("p1(%lf) = %.2lf\n", x, evaluate_polynomial(p1, x));
return 0;
}
```
阅读全文