本题要求实现一个函数,计算阶数为n
,系数为a[0]
... a[n]
的多项式f(x)=∑i=0n(a[i]×xi) 在x
点的值。
函数接口定义:
double f( int n, double a[], double x );
其中n
是多项式的阶数,a[]
中存储系数,x
是给定点。函数须返回多项式f(x)
的值。
裁判测试程序样例:
#include <stdio.h>
#define MAXN 10
double f( int n, double a[], double x );
int main()
{
int n, i;
double a[MAXN], x;
scanf("%d %lf", &n, &x);
for ( i=0; i<=n; i++ )
scanf("%lf", &a[i]);
printf("%.1f\n", f(n, a, x));
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例:
2 1.1
1 2.5 -38.7
输出样例:
-43.1
我的答案:
/*
* 题目中 2 是 n,代表需要累加的项数( n 从 0 开始 )
* 1.1 是 x 代表每次 a[i] 相乘的 x ( i 代表了每次相乘时 x 的指数 ( i = 1, 2 ,3....) )
* 1, 2.5, -38.7 分别代表a[0], a[1], a[2]
*
* 计算过程如下:
* 1. sum += a[0] * x^0 = 1 * ( 1.1^0 ) = 1
* 2. sum += a[1] * x^1 = 2.5 * ( 1.1^1 ) = 1 + 2.5 = 3.5
* 3. sum += a[2] * x^2 = -38.7 * ( 1.1^2 ) = 3.5 + ( -38.7 * 1.21 )
* sum = -42.592
*/
double f( int n, double a[], double x )
{
double sum = 0;
double index = 1; //这里可以设为 0,但设为 0 之后for语句里要增加判断条件
for ( int i = 0; i <= n; i++ )
{
sum += a[i] * index; //第一次计算 index,index 的值为0,x^0 值为1,所以乘以1
index *= x; //第一次计算完之后,index 的值就为 x 了,相当于 x^1
}
return sum;
}
//如下是index = 0的版本,略微复杂一点
/*double f( int n, double a[], double x )
{
double sum = 0;
double index = 0;
for ( int i = 0; i <= n; i++ )
{
if ( i == 0 )
{
sum += a[i];
index = x; //这里为下一次循环做准备,因为第二次开始时,index 的值已为 x
}
else
{
sum += a[i] * index;
index *= x;
}
}
return sum;
}*/