方程也是一种类

来源:互联网 发布:matlab2015b for mac 编辑:程序博客网 时间:2024/04/29 16:02

代码:

#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;    while(1)    {        cin>>e.a>>ch1>>ch2>>e.b>>ch3>>ch4;        if (ch1>='a' && ch1<='z')            if ((ch2=='+' || ch2=='-') && ch3=='=' && ch4=='0') break;        cout<<"输入的方程格式不符合规范,请重新输入\n";    }    if (ch2=='-') e.b=-e.b;    e.unknown=ch1;    return in;}ostream &operator << (ostream &out,CEquation &e){    cout<<e.a<<e.unknown;    if (e.b>=0) cout<<"+";    cout<<e.b<<"=0"<<endl;    return out;}double CEquation::Solve(){    double x;    if (a==0)    {        if (b==0) cout<<"任意一个实数均为方程的解。"<<endl;        else cout<<"方程无解。"<<endl;        return 0;    }    x=-b/a;    return x;}char CEquation::getUnknown(){    return unknown;}int main(){    CEquation e;    cout<<"请输入方程(格式:ax-b=0,a、b为常数,x处是代表未知数的字母):";    cin>>e;    cout<<"方程为:"<<e;    cout<<"方程的解为:"<<e.getUnknown()<<"="<<e.Solve()<<endl;    e.Solve();}


运行结果:

0 0