6-2 多项式求值 (15 分)
函数接口定义:
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
结尾无空行
本题是PTA里固定题目集《基础编程题目集》中第二道,也是非常简单的一道函数题,其操作简单,适合初学者练手。
(本题有更简洁的代码,但这里为了更容易初学者练手,所以打了个麻烦点的)
double f( int n, double a[], double x )
{
int i;
double sum;//总值,最后要返回的就是他
double b[n],c[n];//创建两个容量为n的数组,b[n]用来存储次数,c[n]则用来存储x的i次方,可以合二为一,为了更方便理解,这里采用两个数组
c[0]=1;//c[0]赋值为1,因c[n]里原来没有数,而下面做法又有些类似递归,初值不为1的话会导致结果为0
for(i=0;i<=n;i++)
{
b[i]=i;
}
for(i=0;i<=b[i];i++)
{
c[i+1]=c[i]*x;
}
for(i=0;i<=n;i++)
{
sum=sum+a[i]*c[i];
}
return sum;
}