要了解使用结构的多项式的实现,请参考使用结构的多项式加法。
多项式评估是指为多项式变量的特定值找到多项式表达式的结果。
示例
P(x)= 4x3+6x2+7x+9 where x=2 then,Result = 4(2)3+6(2)2+7(2)1+9 = 4(8)+6(4)+7(2)+9= 32+24+14+9= 79
使用多项式的每个项的结构存储多项式,因此程序使用结构数组。
Struct polynomial { int coefficient; int exponent; };
算法
Eval (struct poly p[10],int n,int x)1.) [Initialize segment variables] [Initialize Counter] Set i=0,sum=02.) Repeat step 3 while i<n 3.) sum=sum+p[i].coeff*pow(x,p[i].expo)4.) Return sum;5.) Exit
#include<iostream> #include<math.h> using namespace std; /* declare structure for polynomial */ struct poly { int coeff; int expo; }; /* function prototypes */ int readPoly(struct poly []); void displayPoly( struct poly [],int terms); int eval(int n1,struct poly []); int main(){ int n1; int value; struct poly p1[20]; cout<<"\n Enter the polynomial details:"; n1=readPoly(p1); cout<<"\n The polynomial is: "; displayPoly(p1,n1); value=eval(n1,p1); cout<<"\n The Resultant value of the polynomial is:"<<value<<endl; return 0; } int readPoly(struct poly p[]) { int t1,i; cout<<"\n Enter the total number of terms in the polynomial: "; cin>>t1; cout<<"\n Enter the COEFFICIENT and EXPONENT "<<endl; for(i=0;i<t1;i++) { cout<<" Enter the Coefficient("<<i+1<<"):"; cin>>p[i].coeff; cout<<" Enter the Exponent("<<i+1<<"):"; cin>>p[i].expo; } return(t1); } void displayPoly(struct poly p[10],int term) { int k; for(k=0;k<term-1;k++) cout<<p[k].coeff<<"(x^"<<p[k].expo<<")+"; cout<<p[k].coeff<<"(x^"<<p[k].expo<<")"; } int eval(int n1,struct poly p1[]) { int i,sum,x; cout<<"\n\n Enter the value of x for evaluation: "; cin>>x; sum=0; for(i=0;i<n1;i++) sum=sum + p1[i].coeff*pow(x,p1[i].expo); return(sum); }
输出结果
Enter the polynomial details: Enter the total number of terms in the polynomial: 4 Enter the COEFFICIENT and EXPONENT Enter the Coefficient(1):4 Enter the Exponent(1):3 Enter the Coefficient(2):6 Enter the Exponent(2):2 Enter the Coefficient(3):7 Enter the Exponent(3):1 Enter the Coefficient(4):9 Enter the Exponent(4):0 The polynomial is: 4(x^3)+6(x^2)+7(x^1)+9(x^0) Enter the value of x for evaluation: 2 The Resultant value of the polynomial is:79