PAT基础编程题目集——6-2 多项式求值

版权声明:余生请多指教,欢迎交流学习: https://blog.csdn.net/LYS20121202/article/details/83032815

原题目:

本题要求实现一个函数,计算阶数为n,系数为a[0] ... a[n]的多项式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

分析 :

1.由数组保存的系数可通过for或while循环调用,对于阶数的乘法,可使用pow()函数来让运算更为简单

                                                pow()函数的用法→pow(x,y)   x的y次方

2.注意值的类型是int 还是double

代码:

double f( int n, double a[], double x )
{
    int i;
    double sum=0.0;
    for(i=0;i<=n;i++)
    {
        sum+=a[i]*pow(x,i);
    }
    return sum;
}

猜你喜欢

转载自blog.csdn.net/LYS20121202/article/details/83032815