pat乙1062 最简分数
作者:互联网
#include<iostream>
using namespace std;
struct fraction{//分数结构体
int up;
int down;
fraction()
{
}
};
int gcd(int a,int b)//最大公约数
{
if(b==0)return a;
else return gcd(b,a%b);
}
bool isbig(fraction a,fraction b)//比较分数大小
{
int theup=a.up*b.down-a.down*b.up;
if(theup>0)return 1;
else return 0;
}
bool iseasy(fraction a)//是否为最简分数
{
int i=gcd(a.up,a.down);
if(i==1)return 1;
else return 0;
}
int main()
{
fraction a,b,c;
int i,n=0,k,themax,thegcd,themin,temp;
float maxup,minup;
char c1;
cin>>a.up>>c1>>a.down;
cin>>b.up>>c1>>b.down;
cin>>k;
if(isbig(a,b))//使b为较大的分数
{
temp=a.up;
a.up=b.up;
b.up=temp;
temp=a.down;
a.down=b.down;
b.down=temp;
}
thegcd=gcd(b.down,k);
maxup=1.0*b.up/(b.down/thegcd)*(k/thegcd);//求分子上界
themax=int(maxup);
if(themax==maxup)themax--;
thegcd=gcd(a.down,k);
minup=1.0*a.up/(a.down/thegcd)*(k/thegcd);//求分子下界
themin=int(minup);
themin++;
for(i=themin;i<=themax;i++)//计算最简分数个数
{
a.up=i;
a.down=k;
if(iseasy(a))
{
n++;
}
}
for(i=themin;i<=themax;i++)
{
a.up=i;
a.down=k;
if(iseasy(a))//是最简分数则输出
{
n--;
cout<<a.up<<"/"<<a.down;
if(n!=0)//按格式输出
{
cout<<" ";
}
}
}
return 0;
}
chang_sheng1
发布了46 篇原创文章 · 获赞 0 · 访问量 2035
私信
关注
标签:简分数,pat,int,1062,up,down,fraction,thegcd,return 来源: https://blog.csdn.net/chang_sheng1/article/details/104118459