SLIDE1

Thursday, March 5, 2015

rút gọn phân số trong lập trình c/c++

rút gọn phân số trong lập trình c/c++

//rút gọn phân số
#include<iostream>
using namespace std;
struct phanso
{
int tu,mau;
};
void nhap(phanso &x)
{
char s[100],c[100];
int i,j,kt,d,dem;
do{
kt=0;
cout<<"\nnhap phan so dang a/b: ";
gets(s);
dem=0;d=0;
for(i=0;i<strlen(s);i++)
{
if(s[i]=='/' || (s[i]>='0' && s[i]<='9')) dem++;
if(s[i]=='/') d++;
}
if(dem!=strlen(s) || d!=1)
{
kt=1;
cout<<"\nloi dinh dang!";
continue;
}
i=0;
while(s[i]!='/') c[i]=s[i++];
c[i]='\0';
x.tu=atoi(c);
d=0;
for(j=i+1;j<strlen(s);j++) c[d++]=s[j];
c[d]='\0';
x.mau=atoi(c);
if(x.mau==0)
{
kt=1;
cout<<"\nloi toan hoc!";
}
}while(kt);
}
void xuat(phanso x)
{
cout<<x.tu<<"/"<<x.mau;
}
void rutgon(phanso &x)
{
int a=abs(x.tu),b=abs(x.mau);
if(a==0) return;
while(a!=b)
if(a>b) a-=b;
else b-=a;
x.tu/=a;
x.mau/=a;
}
void main()
{
phanso a;
nhap(a);
xuat(a);
rutgon(a);
cout<<"=";
xuat(a);
system("pause");
}