题目要求
已知某基类已提供求 Δ \Delta Δ的算法,编程用派生类继承该算法并求一元二次方程的实根和虚根(要求有出错提示)。
代码
#include<iostream>
#include<cmath>
using namespace std;
class CBase
{
private:
float a,b,c,d;
public:
float delta(float a,float b,float c)
{
d=b*b-4*a*c;
return d;
}
};
class CDerive:public CBase
{
private:
float x1,x2,real_part,imag_part,x;
public:
void great(float a,float b,float d)
{
x1 = ( -b + sqrt(d)) / (2*a);
x2 = ( -b - sqrt(d)) / (2*a);
cout << "x1 =" << x1 <<endl;
cout << "x2 =" << x2 <<endl;
}
void equal(float a,float b)
{
x = -b/(2*a);
cout << "x1 = x2 = "<< x << endl;
}
void less(float a,float b,float d)
{
real_part = -b / (2*a);
imag_part = sqrt(-d) / (2*a);
cout << "x1 = " << real_part << "+" << imag_part << "i" << endl;
cout << "x2 = " << real_part << "-" << imag_part << "i" << endl;
}
};
int main()
{
float a,b,c,d;
CDerive aa;
cout<<"Input a, b, c:"<<endl;
cin>>a >> b >>c;
d = aa.delta(a,b,c);
while (a==0)
{
cout<<"Please input again"<<endl;
cout<<"Input a, b, c:"<<endl;
cin>>a >> b >>c;
d = aa.delta(a,b,c);
}
if(d > 0)
{
aa.great(a,b,d);
}
else if (d == 0)
{
aa.equal(a,b);
}
else
{
aa.less(a,b,d);
}
system("pause");
}