Thứ Tư, 11 tháng 3, 2015

Viết chương trình nhập vào hai phân số, tìm phân số lớn nhất và xuất kết quả.

//tìm phân số lớn nhất
#include<iostream>
using namespace std;
struct phanso
{
int tu,mau;
};
void nhap(phanso &x);
void xuat(phanso x);
phanso max(phanso x,phanso y);
void main()
{
phanso x,y,z;
cout<<"\nNHAP 2 PHAN SO:\nnhap phan so 1:";
nhap(x);
cout<<"\nnhap phan so 2:";
nhap(y);
cout<<"\nphan so lon nhat la: ";
z=max(x,y);
xuat(z);
system("pause");
}
phanso max(phanso x,phanso y)
{
int a,b;
a=x.tu*y.mau;
b=y.tu*x.mau;
if(a>b) return x;
return y;
}
void xuat(phanso x)
{
cout<<x.tu<<"/"<<x.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);
}

Không có nhận xét nào:

Đăng nhận xét