主题:[讨论]用面向对象设计编写程序一元二次方程
#include<iostream>
#include<math.h>
using namespace std;
class Complex
{
private:
double real,imag;
public:
Complex (double,double);
void set (double,double);
void printf();
};
void Complex::set (double r,double i)
{
real=r;
imag=i;
}
void Complex::printf()
{
cout<<real<<"+"<<imag<<"i"<<endl;
cout<<real<<"-"<<imag<<"i"<<endl;
}
class Equation
{
private:
double a,b,c,delta;
Complex root1,root2;
public:
Equation(double a1,double b1,double c1)
{
a=a1;b=b1;c=c1;
}
bool isEquation()
{
return(a!=0);
}
void countDelta()
{
delta=b*b-4*a*c;
}
Complex getFirstRoot()
{
root1=(-b+sqrt(delta))/2*a;
}
Complex getSecondRoot()
{
root2=(-b-sqrt(delta))/2*a;
}
void resolve()
{ double r1,r2,i1,i2;
if(delta<0)
{
r1=(-b)/2*a;
i1=sqrt(-delta)/2*a;
r2=r1;
i2=i1;
}
else if(delta=0)
{
r1=(-b+sqrt(delta))/2*a;
i1=0;
r2=r1;
i2=0;
}
else
{
r1=(-b+sqrt(delta))/2*a;
i1=0;
r2=(-b-sqrt(delta))/2*a;
i2=0;
}
}
};
void main()
{
double a,b,c;
cout<<"输入方程系数:"<<endl;
cin>>a>>b>>c;
Equation equation=new Equation(a,b,c);
if(equation.isEquation())
{
equation.countDelta();
equation.resolve();
Complex r1=equation.getFirstRoot();
Complex r2=equation.getSecondRoot();
r1.printf();
r2.printf();
}
else
{
cout<<"该方程不是二元一次方程"<<endl;
}
}
但是有错误:
error C2512: 'Complex' : no appropriate default constructor available
#include<math.h>
using namespace std;
class Complex
{
private:
double real,imag;
public:
Complex (double,double);
void set (double,double);
void printf();
};
void Complex::set (double r,double i)
{
real=r;
imag=i;
}
void Complex::printf()
{
cout<<real<<"+"<<imag<<"i"<<endl;
cout<<real<<"-"<<imag<<"i"<<endl;
}
class Equation
{
private:
double a,b,c,delta;
Complex root1,root2;
public:
Equation(double a1,double b1,double c1)
{
a=a1;b=b1;c=c1;
}
bool isEquation()
{
return(a!=0);
}
void countDelta()
{
delta=b*b-4*a*c;
}
Complex getFirstRoot()
{
root1=(-b+sqrt(delta))/2*a;
}
Complex getSecondRoot()
{
root2=(-b-sqrt(delta))/2*a;
}
void resolve()
{ double r1,r2,i1,i2;
if(delta<0)
{
r1=(-b)/2*a;
i1=sqrt(-delta)/2*a;
r2=r1;
i2=i1;
}
else if(delta=0)
{
r1=(-b+sqrt(delta))/2*a;
i1=0;
r2=r1;
i2=0;
}
else
{
r1=(-b+sqrt(delta))/2*a;
i1=0;
r2=(-b-sqrt(delta))/2*a;
i2=0;
}
}
};
void main()
{
double a,b,c;
cout<<"输入方程系数:"<<endl;
cin>>a>>b>>c;
Equation equation=new Equation(a,b,c);
if(equation.isEquation())
{
equation.countDelta();
equation.resolve();
Complex r1=equation.getFirstRoot();
Complex r2=equation.getSecondRoot();
r1.printf();
r2.printf();
}
else
{
cout<<"该方程不是二元一次方程"<<endl;
}
}
但是有错误:
error C2512: 'Complex' : no appropriate default constructor available