一元多项式求值(用C语言实现)
时间: 2024-09-10 15:08:45 浏览: 20
在C语言中,我们可以创建一个函数来计算一元多项式的值。这个函数通常接受三个参数:系数数组、次数(也就是项的数量),以及变量的值。下面是一个简单的例子:
```c
#include <stdio.h>
// 定义函数,接收系数数组、次数和x值作为输入
double polynomial_value(double coefficients[], int degree, double x) {
double result = 0;
for (int i = 0; i <= degree; ++i) { // 循环从0到degree,因为最高次幂需要计算
result += coefficients[i] * pow(x, i); // 乘法运算并应用指数法则pow
}
return result;
}
int main() {
double coefficients[] = {2.0, 1.5, -0.5}; // 例如多项式为2x^2 + 1.5x - 0.5
int degree = sizeof(coefficients) / sizeof(coefficients[0]) - 1; // 计算次数减一
double variable_value = 3.0;
double value = polynomial_value(coefficients, degree, variable_value);
printf("The value of the polynomial at x=%lf is %lf\n", variable_value, value);
return 0;
}
```
在这个例子中,`polynomial_value`函数计算了形如 `a_n*x^n + a_{n-1}*x^(n-1) + ... + a_1*x + a_0` 的一元多项式的值,其中 `coefficients` 数组存储的是各项的系数。