枚举分母,然后离他最近的分子只有两个,分别判断一下能不能用来更新答案即可
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int a,b,aa,ab;
double mx=10;
void wk(int x,int y)
{
if(x*b==y*a)
return;
if(fabs((double)x/y-(double)a/b)<mx)
{
mx=fabs((double)x/y-(double)a/b);
aa=x,ab=y;
}
}
int main()
{
scanf("%d%d",&a,&b);
for(int i=1;i<=32767;i++)
wk(floor((double)a/b*i),i),wk(floor((double)a/b*i)+1,i);
printf("%d %d\n",aa,ab);
return 0;
}