PAT6-2 多项式求值

版权声明:本文为博主原创文章,未经博主允许不得转载。访问本人博客可以百度COCO56,获取更多资讯。有事儿请内信或者在文章下方评论 https://blog.csdn.net/COCO56/article/details/84669272

1.题目描述

题目来源:https://pintia.cn/problem-sets/14/problems/734

基础编程题目集


760 分

  1. 函数题共 13 小题,共计 185 分
  2. 编程题共 38 小题,共计 575 分

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

 2.注意事项

由于题目说你的代码将会被嵌入到测试程序中,因此 无需再定义main函数啥的,直接提交个名字为“f”的函数即可(注意:如果再定义main函数啥的,由于一个程序只能有一个程序入口,会提示编译错误)。

3.答案示例 

1.简单

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

2.速度快

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

猜你喜欢

转载自blog.csdn.net/COCO56/article/details/84669272