1. 程式人生 > >4-2 多項式求值 (15分)

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

程序 for content scan open %d 接口 tex sym

本題要求實現一個函數,計算階數為n,系數為a[0] ... a[n]的多項式f(x)=\sum_{i=0}^{n}(a[i]\times x^i)f(x)=?i=0?n??(a[i]×x?i??) 在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

/* 你的代碼將被嵌在這裏 */
double f(int n, double a[], double x)
{
    double sum=0,temp=1.0;
    for(int i=0;i<=n;i++)
    {
        sum+=a[i]*temp;
        temp*=x;
    }
    return sum;
}

 

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