1. 程式人生 > >C++實現有理數類加減乘除

C++實現有理數類加減乘除

C++上機題,題目如下:
設計一個有理數類,要求如下:
有理數有整數型別的分子、分母組成,通過運算子過載,完成有理數的加、減、乘、除運算,運算結果要求為最簡分數,即分子分母沒有公約數。在主程式中測試類與方法。

不多廢話,完整程式碼我已經貼出來了,註釋也很詳細,唯一要注意的就是分母不能為0和第二個有理數的分子也不能為0(因為除數不能為0)。希望對初學C++,碰巧有類似練習的童鞋有幫助@[email protected]

#include <iostream>
#include <cmath>
//numerator分子  denominator分母
using namespace std;
class Rational {
public
: Rational(int n=0,int d=1):num(n),den(d) {} //有參建構函式 friend Rational operator+(const Rational &r1,const Rational &r2);//相加 friend Rational operator-(const Rational &r1,const Rational &r2);//相減 friend Rational operator/(const Rational &r1,const Rational &r2);//相除 friend Rational operator*(const
Rational &r1,const Rational &r2);//相乘 void simplify();//對有理數進行化簡 void display(); //顯示結果 private : double num; double den; }; Rational operator+(const Rational &r1,const Rational &r2) { Rational r; r.num = r1.den*r2.num+r1.num*r2.den;//相加的分子等於r1分母和r2分子相乘,r1分子和r2分母相乘之和
r.den = r1.den*r2.den;//分母等於兩個有理數分母的相乘 r.simplify();//呼叫simplify對結果進行化簡 return r;//將結果返回 } Rational operator-(const Rational &r1,const Rational &r2) { Rational r; r.num = r1.num*r2.den-r1.den*r2.num;//相加的分子等於r1分母和r2分子相乘,r1分子和r2分母相乘之差 r.den = r1.den*r2.den;//分母等於兩個有理數分母的相乘 r.simplify(); return r; } Rational operator/(const Rational &r1,const Rational &r2) { Rational r; if(r1.den==0||r2.den==0||r2.num==0) { cout<<"分母或者除數不能為0"<<endl; } else if(r1.num==0) { cout<<"0/0"<<endl; } else { r.num = r1.num*r2.den;//相除的分子等於r1分子和r2分母相乘 r.den = r1.den*r2.num;//分母等於兩個r1分母和r2分子相乘 r.simplify(); return r; } } Rational operator*(const Rational &r1,const Rational &r2) { Rational r; if(r1.den==0||r2.den==0) { cout<<"分母不能為0"<<endl; } else if(r1.num==0||r2.num==0) { cout<<"0/0"<<endl; } else { r.num = r1.num*r2.den;//分子等於r1分子和r2分母相乘 r.den = r1.den*r2.num;//分母等於兩個r1分母和r2分子相乘 r.simplify(); return r; } } void Rational::simplify() { int i,j,temp; i=abs(den); j=abs(num); //如果i對j取餘不為0,輾轉相除法求最大公約數 while(temp=i%j) { i=j; j=temp; } den/=j; num/=j; if(den<0) { den=-den; num=-num; } } void Rational::display() { if(num==0||den==0) { } else { cout<<num<<"/"<<den<<endl; } } int main() { Rational r; Rational r1(1,3),r2(0,5); r=r1+r2; r.display(); r=r1-r2; r.display(); r=r1*r2; r.display(); r=r1/r2; r.display(); return 0; }