PAT6-2 多項式求值
阿新 • • 發佈:2018-12-08
1.題目描述
題目來源:https://pintia.cn/problem-sets/14/problems/734
基礎程式設計題目集
760 分
- 函式題共 13 小題,共計 185 分
- 程式設計題共 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;
}