题目链接:
http://202.197.224.59/OnlineJudge2/index.php/Problem/read/id/1236
题意:
给一个小于1的double数,求分母1000以内最接近他的分数。
思路:
穷举分母,求最小误差。开始是gcd写错爆0导致RE,后来发现最大的错误是误差的计算方法出错。没除以i。网上有其他的关于穷举二分的解法。
源码:
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
#define gmax(a,b) a>b?a:b
#define gmin(a,b) a<b?a:b
double zheng(double a)
{
if(a<0) return -a;
return a;
}
int gcd(int a,int b)
{
if(b == 0)
return a;
return gcd(b,a%b);
}
int main()
{
// freopen("data.txt","r",stdin);
// freopen("data1.txt","w",stdout);
double a;
int t;scanf("%d",&t);
while(t--){
scanf("%lf",&a);
int mot,son;
double wucha = 1;
// printf("original is %d %d\n",son,mot);
// cout << "wucha is "<<wucha<<endl;
for(int i=1; i<=1000; i++){
int t1 = a*i + 0.5;
int t2 = a*i;
// double temp = zheng(1.0*t1 / i - a);
double temp = zheng((1.0*t1 - a*i) / i);
// if(i == 373 || i == 933)
// printf("%0.10f\n",temp);
// cout <<"temp is "<< temp <<endl;
if(temp < wucha){
son = a * i + 0.5;
mot = i;
wucha = temp;
}
temp = zheng((1.0*t2 - i * a) / a);
if(temp < wucha){
son = a*i;
mot = i;
wucha = temp;
}
}
int k = gcd(gmax(son,mot),gmin(son,mot));
son /= k;
mot /= k;
printf("%d/%d\n",son,mot);
}
return 0;
}