4-2 多项式求值 (15分)

本题要求实现一个函数,计算阶数为n,系数为a[0] ... a[n]的多项式f(x)=\sum_{i=0}^{n}(a[i]\times x^i)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

反思:
编程序的时候能用库函数的就用库函数,比如PTA中的多项式求值这个题,刚开始按照自己的想法,写两层循环,时间复杂度为n方,当数组很大的时候就会导致程序运行耗费的时间增长,
只能出错啦,通过百度,知道了pow函数的用法,还有多项式求值可以用到化简的方法。
方法一:
1 double f(int n,double a[],double x)
2 {
3     double sum = 0.0;
4     for(;n>=0;n--)
5         sum = sum*x + a[n];
6     return sum;
7 }    

方法二:

 1 #include<math.h>
 2 double f(int n,double a[],double x)
 3 {
 4     double sum=0.0;
 5     int i;
 6     for(i=0; i<=n; i++)
 7     {
 8         sum=sum+a[i]*pow(x,i);
 9     }
10     return sum;
11 }

 

posted @ 2017-08-06 16:22  努力更加美好  阅读(859)  评论(0编辑  收藏  举报