Friday, May 13, 2016

Chương trình về Phân Số với C++ (Chồng toán tử )

//Họ Tên: Trần Văn Linh
//MaSV:581597
//Lớp:K58QLTT

--------------------------------------------------------------------------------------------------------------------------
phanso.cpp
#include<iostream>

using namespace std;

class phanso
{
private:
int mau;
int tu;
public:
phanso();
phanso(float x,float y);
friend istream& operator>>(istream &cin,phanso &ps);
friend ostream& operator<<(ostream &cout,phanso &ps);
phanso operator+(phanso &ps2);
int operator>(phanso &ps2);
};
//===Chuong trinh chinh===
int main()
{
phanso ps[50],tong;
int i,n,j;
cout<<"Nhap so luong phan so:";
cin>>n;

for(i=0;i<n;i++)
{
cout<<"Nhap phan so thu "<<i+1<<":"<<endl;
cin>>ps[i];
}

cout<<"\nCac phan so da nhap la:"<<endl;
for(i=0;i<n;i++)
cout<<ps[i]<<"\t";
//sap xep
for(i=0;i<n;i++)
for(j=n-1;j>i;j--)
if(ps[j-1]>ps[j])
{
phanso temp=ps[j];
ps[j]=ps[j-1];
ps[j-1]=temp;
}
cout<<"\nCac phan so da nhap sau khi sap xep la:"<<endl;
for(i=0;i<n;i++)
cout<<ps[i]<<"\t";

tong=ps[0];
for(i=1;i<n;i++)
tong=tong+ps[i];
cout<<"\nTong cua cac phan so la:";
cout<<tong;
return 0;
}
//===Dinh nghia ham===
//---hàm tạo----
phanso::phanso():tu(0),mau(0)
{

}
//----------
phanso::phanso(float x,float y):tu(x),mau(y)
{

}
//------hàm nhập phân số--------
istream& operator>>(istream &cin,phanso &ps)
{
do
{
cout<<"Nhap tu so:";
cin>>ps.tu;
cout<<"Nhap mau so:";
cin>>ps.mau;
if(ps.mau==0)
cout<<"Mau phai khac 0,nhap lai:"<<endl;
}while(ps.mau==0);
return cin;
}
//-----hàm hiện phân số--------
ostream& operator<<(ostream &cout,phanso &ps)
{
int uc;
int a=ps.tu;
int b=ps.mau;

while(a!=0&&b!=0)
if(a>b)
a=a-b;
else
b=b-a;
if(a==0)
uc=b;
else
uc=a;
cout<<ps.tu/uc<<"/"<<ps.mau/uc<<endl;

return cout;
}
//-----hàm cộng hai phân số
phanso phanso::operator+(phanso &ps2)
{
phanso tong;
tong.tu=tu*ps2.mau+ps2.tu*mau;
tong.mau=mau*ps2.mau;
return tong;
}
//----hàm so sánh hai phân số----
int phanso::operator>(phanso &ps2)
{
return (tu*ps2.mau>ps2.tu*mau);
}
//----------

0 comments:

Post a Comment