//用鏈表求多項式的值
#include <iostream>
#include <time.h>
using namespace std;
class Factor
{
public:
float coeff;
int Exp;
};
class PolyTerm
{
public:
int Length;
Factor *fac;
void Create_PolyTerm();
int GetValue(float x);
void Show_PolyTerm();
};
void PolyTerm::Create_PolyTerm()
{
srand(time(NULL));
Length=int(rand()%12);
float Max,Min;
fac=new Factor[Length+1];
for (int i=0;i<=Length;i++)
{
Max=float(rand()%640);
Min=float(1.0+rand()%480);
fac[i].coeff=Max/Min;
fac[i].Exp=i;
}
}
void PolyTerm::Show_PolyTerm()
{
int i;
cout<<"多項式爲:"<<endl;
cout<<fac[0].coeff<<"*X^0";
for (i=1;i<=Length;i++)
{
cout<<"+"<<fac[i].coeff<<"*X^"<<fac[i].Exp;
}
cout<<endl;
}
int PolyTerm::GetValue(float x)
{
float sum,sum_x;
int Exp,i;
sum=0.0;
sum_x=1.0;
Exp=0;
i=1;
while(i<=Length)
{
Exp=1;
sum_x=1.0;
while(Exp<=fac[i].Exp)
{
sum_x*=x;
Exp+=1;
}
sum+=sum_x*fac[i].coeff;
i+=1;
}
sum+=fac[0].coeff;
cout<<"總和爲:"<<sum<<endl;
return 1;
}
int main()
{
PolyTerm by;
float x;
by.Create_PolyTerm();
by.Show_PolyTerm();
cout<<"請輸入X的值:";
cin>>x;
if (by.GetValue(x))
return 1;
else
{
cout<<"求和失敗!"<<endl;
return 0;
}
}
嚴蔚敏2.39
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.