Thứ Ba, 15 tháng 1, 2013

Lập trình hướng đối tượng C++, Phân số


Lập trình hướng đối tượng trên C++
Bài toán phân số.
File PhanSo.h
#include <iostream>
using namespace std;
class phanso
{
private:
int tu,mau;
public:
phanso(int t=0,int m=1)
{
tu=t;
mau=m;
//rutgon();
}
//toán tử gán
void operator=(phanso& p)
{
tu=p.tu;
mau=p.mau;
}
void rutgon();
friend istream& operator>>(istream& is,phanso& ps); //toán tử nhập
friend ostream& operator<<(ostream& os,const phanso& ps); //toán tử xuất
//cac toan tu
friend phanso operator+(const phanso& ps1,const phanso& ps2);
friend phanso operator-(const phanso& ps1,const phanso& ps2);
friend phanso operator*(const phanso& ps1,const phanso& ps2);
friend phanso operator/(const phanso& ps1,const phanso& ps2);
//cac toan tu so sanh
friend bool operator==(const phanso& ,const phanso& );
friend bool operator!=(const phanso& ps1,const phanso& ps2);
friend bool operator>(const phanso& ps1,const phanso& ps2);
friend bool operator<(const phanso& ps1,const phanso& ps2);
};

File PhanSo.cpp

#include "phanso.h"
#include <iostream>
using namespace std;
 istream& operator>>(istream& is,phanso& ps)
 {
cout<<"\nNhap tu so=";
is>>ps.tu;
cout<<ps.tu;
cout<<"\nNhap mau so=";
do{
if(ps.mau==0)
cout<<"\nBan nhap sai! Nhap lai: ";
is>>ps.mau;
}while(ps.mau==0);
if(ps.mau<0) //doi dau
{
ps.tu=-ps.tu;
ps.mau=-ps.mau;
}
ps.rutgon();
return is;
 }
 ostream& operator<<(ostream& os,const phanso& ps)
 {
{
if(ps.tu==0)
os<<"\nKQ Phan so=0 "<<endl;
if(ps.tu==ps.mau)
os<<"\nKQ Phan so=1"<<endl;
else
os<<"\nKQ Phan so= "<<ps.tu<<"/"<<ps.mau<<endl;
}
return os;
 }
 // ham rut gon
int USCLN(int a,int b)
{
int x;
while(b!=0)
{
x=a%b;
a=b;
b=x;
}
return a;
}
void phanso::rutgon()
{
if(mau<0)
{
tu=-tu;
mau=-mau;
}
int u=USCLN(tu,mau);
tu=tu/u;
mau=mau/u;
}

 //ham cong 2 phan so
 phanso operator+(const phanso& ps1,const phanso& ps2)
 {
phanso c;
if(ps1.tu==0)
{
c.tu = ps2.tu;
c.mau = ps2.mau;
}
if(ps2.tu==0)
{
c.tu=ps1.tu;
c.mau=ps1.mau;
}
else
{
c.tu=ps1.tu*ps2.mau+ps2.tu*ps1.mau;
   c.mau=ps1.mau*ps2.mau;
}
c.rutgon();
return c;
 }
 phanso operator-(const phanso& ps1,const phanso& ps2)
 {
return phanso(ps1.tu*ps1.mau-ps2.tu*ps1.mau,ps1.mau*ps2.mau);
 }
  phanso operator*(const phanso& ps1,const phanso& ps2)

 {
return phanso(ps1.tu*ps2.tu,ps1.mau*ps2.mau);
 }

phanso operator/(const phanso& ps1,const phanso& ps2)
 {
 return phanso(ps1.tu*ps2.mau,ps1.mau*ps2.tu);
 }

File Main.cpp

int main()
{
phanso a,b;
phanso c;
cout<<"\nNhap phan so a:";
cin>>a;
cout<<"\nNhap phan so b:";
cin>>b;
cout<<a;
cout<<b;
c=a+b;
cout<<"\nTong a+b"<<c;
system("Pause");

}



1 nhận xét:

Unknown nói...

o de vay

Đăng nhận xét

 
Phạm Quốc Đạt-ĐH Công Nghệ Thông Tin-ĐH Quốc Gia Tp.Hồ Chí Minh --Email: Dat.Pham2@sv.uit.edu.vn