Xây dựng lớp Phânsố trong C++


Tạo lớp Phân số có các thành phần sau:
- Các thuộc tính: ts,ms;
- Hàm tạo có sử dụng tham số mặc định
- Nạp chồng các toán tử sau:
+ Toán tử cộng (+)
+ Toán tử trừ (-)
+ Toán tử nhân ( * )
+ Toán tử chia (/)
+ Toán tử nhập (>>)
+ Toán tử xuất (<<)


#include "iostream.h"
#include "conio.h"
#include "math.h"
class PS
{
     int t,m;
     public:
     friend ostream& operator<<(ostream& os, PS p);
     friend istream& operator>>(istream& is, PS &p);
     friend PS rutgon(PS p);
     PS operator+(PS p);
     PS operator-(PS p);
     PS operator*(PS p);
     PS operator/(PS p);
};

int USCLN(int x,int y)
{
   if(x==0)
     return y;
   if (y==0)
       return x;
   while (x!=y)
      {
        if(x>y)
         x-=y;
        else
         y-=x;
      }
}

ostream& operator<<(ostream& os, PS p)
{
           os<<p.t<</<<p.m<<endl;
           return os;
}

istream& operator>>(istream& is, PS &p)
{
      is>>p.t>>p.m;
      return is;
}

PS rutgon(PS p)
{
      PS q;
      int x;
      x=uscln(p.t,p.m);
      q.t=p.t/x;
      q.m=p.m/x;
       return q;
}

PS PS::operator+(PS p)
{
      PS q;
      q.t=t*p.m+p.t*m;
      q.m=m*p.m;
      return rutgon(q);
}

PS PS::operator-(PS p)
{
    PS q;
   q.t=t*p.m-p.t*m;
   q.m=m*p.m;
   return rutgon(q);
}

PS PS::operator*(PS p)
{
    PS q;
    q.t=t*p.t;
    q.m=m*p.m;
    return rutgon(q);
}

PS PS::operator/(PS p)
{
    PS q;
    q.t=t*p.m;
    q.m=m*p.t;
    return rutgon(q);
}

void main()
{
     PS p1,p2,p;
    cout<<"Nhap p1=";cin>>p1;
    cout<<"Nhap p2=";cin>>p2;
    p=p1+p2;
   cout<<"p="<<p<<endl;
   getch();
}

Comments

Popular posts from this blog

Khoá luyện thi đại học đảm bảo 2012

10 chiêu tăng tuổi thọ cho pin laptop

Viết bài như thế nào để tốt cho SEO