PTA基礎程式設計題目集6-2多項式求值(函式題)
阿新 • • 發佈:2019-01-11
本題要求實現一個函式,計算階數為n
,係數為a[0]
... a[n]
的多項式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
1 double f( int n, double a[], double x ) 2 { 3 double sum=0; 4 double e=1; 5 int i; 6 for(i=0;i<=n;i++) 7 { 8 sum+=a[i]*e; 9 e=e*x; 10 } 11 return sum; 12 }
時間複雜度O(n) 用一個for迴圈即可解決問題。