01./* 02.* 程式的著作權和版本聲明部分 03.* Copyright (c)2013, 煙台大學電腦學院學生 04.* All rightsreserved. 05.* 檔案名稱:CEquation .cpp 06.* 作 者:趙冠哲 07.* 完成日期:2013年5月7日 08.* 版本號碼: v1.0 09.* 輸入描述: 10.* 問題描述: 11.*/ #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 &input,CEquation &e){char ch1,ch2,ch3,ch4;while(1){input>>e.a>>ch1>>ch2>>e.b>>ch3>>ch4;if(ch1>='a'&&ch1<='z')if((ch2=='+'||ch2=='-')&& ch3=='='&&ch4=='0') break;cout<<"您輸入的方程格式不規範,請重新輸入!"<<endl;}if(ch2=='-') e.b=-e.b;e.unknown=ch1;return input;}ostream &operator << (ostream &output,CEquation &e){ cout<<e.a<<e.unknown; if (e.b>=0) cout<<"+"; cout<<e.b<<"=0"<<endl; return output;}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<<"請輸入一元一次方程(輸入格式:3x-8=0):";cin>>e; //在兩次測試中,分別輸入3x-8=0和5s+18=0cout<<"方程為:"<<e;cout<<"方程的解為:"<<e.getUnknown()<<"="<<e.Solve()<<endl;e.Solve();return 0;}
運行結果: