目录
题目:
本题要求实现一个函数,计算阶数为n
,系数为a[0]
... a[n]
的多项式在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
结尾无空行
分析:
把每一项求出来再相加就好了,但是要注意测试点中有一个很大的N,时间限制,x的i次方不能每次都一个一个乘,比如下面这个代码就会运行超时
double f(int n, double a[], double x) {
double s = 0 , s1;
for (int i = 0; i <= n; i++) {
s1 = 1;
for(int i1 = 0; i1 < i; i1++){
s1 *= x;
}
s += a[i] * s1;
}
return s;
}
答案:
double f(int n, double a[], double x) {
double s = 0, s1=1/x;
for (int i = 0; i <= n; i++) {
s1 *= x;
s += a[i] * s1;
}
return s;
}
整个程序的代码:
#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;
}
double f(int n, double a[], double x) {
double s = 0, s1 = 1 / x;
for (int i = 0; i <= n; i++) {
s1 *= x;
s += a[i] * s1;
}
return s;
}