findRoot.h
#if !defined(FINDROOT_H)
#define FINDROOT_H
#include <iostream>
#include <cmath>
using namespace std;
class findRoot
{
private:
float a,b,c,d;
double x1,x2;
public:
findRoot(float x, float y, float z);
~findRoot();
void display();
protected:
int flag();
void one();
void two();
void two_c();
};
#endif
findRoot.cpp
#include "findRoot.h"
findRoot::findRoot(float x, float y, float z)
{
a=x;
b=y;
c=z;
}
findRoot::~findRoot()
{
}
int findRoot::flag()
{
if(a==0)
return -1;
d=(b*b)-(4*a*c);
if(d<0)
two_c();
else if(d==0)
one();
else if(d>0)
two();
return 0;
}
void findRoot::display()
{
if(flag() == -1)
{
cout<<"Input error ..."<<endl;
return;
}
cout<<"x1= "<<x1<<" x2= "<<x2<<endl;
cout<<endl;
}
void findRoot::one()
{
x1=x2=(-b)/(2*a);
}
void findRoot::two()
{
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
}
void findRoot::two_c()
{
x1=(-b)/(2*a);
x2=sqrt(-d)/(2*a);
}
主函数main.cpp
#include "findRoot.h"
void read(float &a, float &b, float &c)
{
cout<<"Input a :";
cin>>a;
cout<<"Input b :";
cin>>b;
cout<<"Input c :";
cin>>c;
}
void main()
{
float a,b,c;
cout<<"Get root of ax2+bx+c=0."<<endl;
for(;;)
{
read(a, b, c);
findRoot obj(a, b, c);
obj.display();
}
}