class root
{
public:
const double m_x1;//一元二次方的第一个根
const double m_x2;//一元二次方的第二个根
const int m_NumOfRoot;//根的个数
//创建一个无实根的对象
root() :m_x1(0.0), m_x2(0.0), m_NumOfRoot(0){}
//创建一个有两个相同根的对象
root(double root) :m_x1(root), m_x2(root), m_NumOfRoot(1){}
//创建一个两个不同根的对象
root(double root1, double root2) :m_x1(root1), m_x2(root2), m_NumOfRoot(2){}
void show() const
{
cout << " ";
switch(m_NumOfRoot)
{
case 0: cout << "无实根" << endl; break;
case 1: cout << "两个相同的实根是:" << m_x1 << endl; break;
default:cout << "两个实根是:" << m_x1 << "和" << m_x2 << endl;
}
}
};
class quadratic//二次方程
{
public:
const double a, b, c;
quadratic(double a, double b, double c) :a(a), b(b), c(c){}
quadratic(quadratic& x):a(x.a), b(x.b),c(x.c){}
quadratic add(quadratic& x)const
{
return quadratic(a + x.a, b + x.b, c + x.c);
}
quadratic sub(quadratic& x)const
{
return quadratic(a - x.a, b - x.b, c - x.c);
}
double value(double x)const { return a*x*x + b*x + c; }
root iroot()const
{
double delta = b*b - 4 * a*c;
if (delta < 0.0)return root();
if (delta == 0.0) return root(-b / (2 * a));
double sq = sqrt(delta);
return root((-b + sq) / (2 * a), (-b - sq) / (2 * a));
}
void show()const
{
cout << endl << a << "X^2" /*showpos*/ << b << "X" <<c/*noshowpos*/;
}
void showFunction(){ show(); cout << "=0.0"; }
};
int main()
{
quadratic q1(3.0, 4.0, 5.0), q2(4.5, 6.0, 2.0), q3(q2.sub(q1));
q1.showFunction();
q1.iroot().show();
q2.showFunction();
q2.iroot().show();
q3.showFunction();
q3.iroot().show();
cout << endl;
return 0;
}