第八週(專案三1)——分數類中的運算子過載.
阿新 • • 發佈:2019-01-22
/* *煙臺大學計算機學院學生 *All right reserved. *檔名稱*煙臺大學計算機學院學生 *All right reserved. *檔名稱:分數類中的運算子過載 *作者:王洪海 *完成日期:2013年4月20日 *版本號:v1.0 *對任務及求解方法的描述部分:分數類中的運算子過載 *我的程式: */ #include<iostream> using namespace std; class CF { private: int nume; // 分子 int deno; // 分母 public: CF (int nu=0,int de=1); void set(int nu,int de); //置值,改變值時用 void simplify(); //化簡(使分子分母沒有公因子) void output(); //輸出:以8/6為例,style為0時,原樣輸出8/6; CF operator+ (CF &t); CF operator- (CF &t); CF operator* (CF &t); CF operator/ (CF &t); bool operator> (CF &t); bool operator< (CF &t); bool operator== (CF &t); bool operator>= (CF &t); bool operator<= (CF &t); bool operator!= (CF &t); }; CF::CF(int nu,int de) { nume=nu; deno=de; } void CF::set(int nu,int de) { nume=nu; deno=de; } void CF::simplify() { int i; int p; if(nume>deno) p=deno; else p=nume; for(i=2;i<=p;i++) { if(nume%i==0&&deno%i==0) { nume/=i; deno/=i; } } } void CF::output() { cout<<nume<<"/"<<deno<<endl; } CF CF::operator+ (CF &t) { CF t3; int n; if(deno==t.deno) { t3.deno=deno; t3.nume=nume+t.nume; } else { t3.deno=deno*t.deno; n=nume*t.deno; t3.nume=n+deno*t.nume; } return t3; } CF CF::operator- (CF &t) { CF t3; if(deno==t.deno) { t3.deno=deno; t3.nume=nume-t.nume; } else { t3.deno=deno*t.deno; t3.nume=nume*t.deno-deno*t.nume; } return t3; } CF CF::operator* (CF &t) { CF t3; t3.nume=nume*t.nume; t3.deno=deno*t.deno; return t3; } CF CF::operator/(CF &t) { CF t3; t3.deno=deno*t.nume; t3.nume=nume*t.deno; return t3; } bool CF::operator> (CF &t) { int z1,z2; z1=nume*t.deno; //先把兩個分數同分,只比較分子大小 z2=t.nume*deno; if(z1>z2) return true; return false; } bool CF::operator< (CF &t) { int z1,z2; z1=nume*t.deno; //先把兩個分數同分,只比較分子大小 z2=t.nume*deno; if(z1<z2) return true; else return false; } bool CF::operator== (CF &t) { int z1,z2; z1=nume*t.deno; //先把兩個分數同分,只比較分子大小 z2=t.nume*deno; if(z1==z2) return true; else return false; } bool CF::operator>= (CF &t) { if(*this<t) return false; else return true; } bool CF::operator<= (CF &t) { if(*this>t) return false; else return true; } bool CF::operator!= (CF &t) { if(*this==t) return false; else return true; } int main() { CF t1(2,3),t2(4,5),t; cout<<"原本兩個分數分別為:"<<endl; t1.output(); t2.output(); cout<<"兩個分數相加得: "; t=t1+t2; t.simplify(); t.output(); cout<<"兩個分數相減得: "; t=t1-t2; t.simplify(); t.output(); cout<<"兩個分數相乘得: "; t=t1*t2; t.simplify(); t.output(); cout<<"兩個分數相除得: "; t=t1/t2; t.simplify(); t.output(); cout<<"對兩個分數進行比較:"<<endl; if(t1>t2) cout<<"t1>t2"<<endl; if(t1<t2) cout<<"t1<t2"<<endl; if(t1==t2) cout<<"t1=t2"<<endl; if(t1!=t2) cout<<"t1不等於t2"<<endl; if(t1>=t2) cout<<"t1等於或大於t2"<<endl; if(t1<=t2) cout<<"t1等於或小於t2"<<endl; return 0; }
執行結果,如下圖:
眾裡找錯千百度,驀然回首那錯就在傳值處!!!