PTA基礎編程題目集6-2多項式求值(函數題)


本題要求實現一個函數,計算階數為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循環即可解決問題。

 
         
         
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM