[问答题]

```class Root
{
public:
const Complex& Solve();
...
};```

```//----------------------------------
//Complex.h
//-----------------------------------
#include<iostream>
using namespace std;
//-----------------------------------
class Complex{
protected；
double re, im;
public:
Complex(double r=0, double v=0):re(r),im(v){}
friend Complex operator+(const Complex& a, const Complex& b);
friend ostream& operator<<(ostream& out, const Complex& a);
};//---------------------------------

```//-----------------------------------
//Complex.h
//-----------------------------------
#include"Complex.h"
#include<iostream>
using namespace std;
//-----------------------------------
ostream& operator<<(ostream& out, const Complex& a){
return (a.im ? cout<<a.re<<" + "<<a.im<<"i" : cout<<a.re);
}//----------------------------------
Complex operator+(const Complex& a, const Complex& b){
return Complex(a.re+b.re, a.im+b.im);
}//----------------------------------```

```//-----------------------------------
//Root.h
//-----------------------------------
#include<iostream>
using namespace std;
//-----------------------------------
class Root{
double aa,bb,cc;
public:
Root(double a, double b, double c):aa(a), bb(b), cc(c) {}
void solve()const;
};//---------------------------------

```//-----------------------------------
//Root.cpp
//-----------------------------------
#include"Root.h"
#include"Complex.h"
#include<cmath>    // for sqrt()
//-----------------------------------
void Root::solve()const{
Complex x1(-bb/(2*aa)), x2(x1);
double delta = bb*bb - 4*aa*cc;
if(delta){                       // delta为0则不做处理
bool flag=delta<0;
if(flag)delta = -delta;
delta - std::sqrt(delta)/(2*aa);
if(flag) x1.im = delta, x2.im = -delta;       //复根
else        x1.re += delta, x2.re -= delta;   //实根
}
cout<<"The solution is\n";
cout<<" x1 = "<<x1<<"\n";
cout<<" x2 = "<<x2<<"\n";
}//----------------------------------```

```//-----------------------------------
//EX1101.cpp
//解方程
//-----------------------------------
#include"Root.h"
#include<iostream>
using namespace std;
//-----------------------------------
int main() {
for(double a,b,c; cin>>a>>b>>c; )
Root(a,b,c).solve();
}//----------------------------------```

1 2 3
3 7 3

The solution is
x1 = -1 + 1.41421i
x2 = -1 + -1.41421i
The solution is
x1 = -0.565741
x2 = -1.76759

1条回答 948浏览

# 相关试题

• 扫描二维码，关注牛客网

• 下载牛客APP，随时随地刷题