#include<iostream>
using namespace std;
class CEquation
{
private:
double a; // 未知数系数
double b; // 常数项
char unknown; // 代表未知数的符号
public:
CEquation(double aa=0,double bb=0);
friend istream &operator >> (istream &in,CEquation &e);
friend ostream &operator << (ostream &out,CEquation &e);
double Solve();
char getUnknown();
};
CEquation::CEquation(double aa,double bb)
{
a=aa;
b=bb;
}
istream &operator>>(istream &in,CEquation &e)
{
char ch1,ch2,ch3,ch4;
cout<<"请输入方程:"<<endl;
while(1)
{
cin>>e.a>>ch1>>ch2>>e.b>>ch3>>ch4;
if(ch1=='x'&&((ch2=='+')||(ch2=='-'))&&ch3=='='&&ch4=='0')
break;
cout<<"格式输入错误,请重新输入";
}
if(ch2=='-')
e.b=-e.b;
e.unknown=ch2;
return in;
}
ostream &operator<<(ostream &out,CEquation &e)
{
cout<<e.a<<"x";
if(e.b>0)
cout<<"+"<<e.b<<"=0";
else
cout<<e.b<<"=0"<<endl;
return out;
}
double CEquation::Solve()
{
if(a==0)
cout<<"方程无解";
return -b/a;
}
char CEquation::getUnknown()
{
return unknown;
}
int main()
{
CEquation e;
cout<<"请输入方程(格式:ax-b=0,a、b为常数,x处是代表未知数的字母):";
cin>>e; //在两次测试中,分别输入3x-8=0和50s+180=0
cout<<"方程为:"<<e;
cout<<"方程的解为:"<<"x="<<e.Solve()<<endl; //对两次测试,分别输出x=...和s=...
e.Solve();
}