#include <iostream.h>
#include <math.h>
class Quadratic
{
double a,b,c;
public:
Quadratic(){a=b=c=0;}
Quadratic(double aa,double bb,double cc);
Quadratic operator+(Quadratic &x);
Quadratic operator-(Quadratic &x);
double Compute(double x);
int Root(double &r1,double &r2);
void Print();
};
Quadratic Quadratic::operator+(Quadratic &x)
{
Quadratic m;
m.a=a+x.a;
m.b=b+x.b;
m.c=c+x.c;
return m;
}
Quadratic Quadratic::operator-(Quadratic &x)
{
Quadratic n;
n.a=a-x.a;
n.b=b-x.b;
n.c=c-x.c;
return n;
}
double Quadratic::Compute(double x)
{
return a*x*x+b*x+c;
}
int Quadratic::Root(double &r1,double &r2)
{
if(a==0)
{
cout<<"不是一元二次函数"<<endl; return -1;
}
if(b*b-4*a*c==0)
{
r1=r2=(-b)/2*a; return 1;
}
if(b*b-4*a*c<0)
{
cout<<"无实根"<<endl; return 0;
}
else
{ r1=(-b)+sqrt(b*b-4*a*c)/(2*a);
r2=(-b)-sqrt(b*b+4*a*c)/(2*a);
return 1;
}
}
void Quadratic::Print()
{
if(b<0 && c<0)
{
cout<<a<<"x**2"<<b<<"x"<<c<<endl;
}
if(b<0 && c>0)
{
cout<<a<<"x**2"<<b<<"x"<<"+"<<c<<endl;
}
if(b>0 && c<0)
{
cout<<a<<"x**2"<<"+"<<b<<"x"<<c<<endl;
}
}
Quadratic::Quadratic(double aa,double bb,double cc)
{
a=aa;
b=bb;
c=cc;
}
void main()
{
double a,b,c,x;
double r1,r2;
double a1,a2,b1,b2,c1,c2;
cout<<"请输入方程三个系数a,b,c的值:"<<endl;
cout<<"a= ";cin>>a;
cout<<"b= ";cin>>b;
cout<<"c= ";cin>>c;
Quadratic p1(a,b,c);
cout<<"该函数是: "<<endl;
p1.Print();
cout<<"该函数为零的两个根是: "<<endl;
p1.Root(r1,r2);
if(p1.Root(r1,r2)==0)
cout<<".";
else
cout<<r1<<" "<<r2<<endl;
cout<<"请输入一个X值: "<<endl;
cin>>x;
cout<<"当输入X的值为: "<<x<<"时该函数的值为: "<<endl;
p1.Compute(x);
cout<<p1.Compute(x)<<endl;
cout<<endl;
cout<<"p2 and p3"<<endl;
cin>>a1>>a2>>b1>>b2>>c1>>c2;
Quadratic p2(a1,b1,c1),p3(a2,b2,c2),p4;
p2.Print();
p3.Print();
p4=p2+p3;
p4.Print();
cout<<endl;
}