1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| class fraction { public: int MaxNum(int a,int b); fraction(int u_,int d_){num_u=u_;num_d=d_;} fraction(){num_u=0;num_d=0;} void Display(); void Sample();
int operator == (fraction a1); friend fraction operator + (fraction a1,fraction a2); friend fraction operator - (fraction a1,fraction a2); friend fraction operator * (fraction a1,fraction a2); friend fraction operator / (fraction a1,fraction a2);
private: int num_u; int num_d; };
int fraction::MaxNum(int a,int b) { Swap(a,b); if(a==0) return b; return MaxNum(b-a,a); }
void fraction::Display() { Sample(); if(num_u==0) cout << "0" << endl; else { if(num_d==1&&num_u!=0) cout << num_u << endl; else cout << num_u << "/" << num_d << endl; } }
void fraction::Sample() { int b=MaxNum(num_u,num_d); num_u=num_u / b; num_d=num_d /b; }
int fraction::operator == (fraction a1) { int d; d=MaxNum(num_d,num_u); num_u=num_u / d; num_d=num_d / d; d=MaxNum(a1.num_d,a1.num_u); a1.num_u=a1.num_u / d; a1.num_d=a1.num_d / d; if(a1.num_u==num_u&&a1.num_d==num_d) return 1; return 0; }
fraction operator + (fraction a1,fraction a2) { fraction c; c.num_d=a1.num_d * a2.num_d; c.num_u=a1.num_u * a2.num_d + a2.num_u *a1.num_d; return c; }
fraction operator - (fraction a1,fraction a2) { fraction c; c.num_d=a1.num_d * a2.num_d; c.num_u=a1.num_u * a2.num_d - a2.num_u *a1.num_d; return c; }
fraction operator * (fraction a1,fraction a2) { fraction c; c.num_d=a1.num_d * a2.num_d; c.num_u=a1.num_u * a2.num_u; return c; }
fraction operator / (fraction a1,fraction a2) { fraction c; c.num_d=a1.num_d * a2.num_u; c.num_u=a1.num_u * a2.num_d; return c; }
int main() { fraction c(12,72); c.Display(); int d=c.MaxNum(12,72); cout << d << endl;
fraction m(1,6); if(m==c) cout << "相等\n";
fraction e; e=m + c; e.Display(); e=m - c; e.Display(); e=m * c; e.Display(); e=m / c; e.Display();
return 0; }
|