Fraction | ||
Accepted : 145 | Submit : 956 | |
Time Limit : 1000 MS | Memory Limit : 65536 KB |
FractionProblem Description:Everyone has silly periods, especially for RenShengGe. It's a sunny day, no one knows what happened to RenShengGe, RenShengGe says that he wants to change all decimal fractions between 0 and 1 to fraction. In addtion, he says decimal fractions are too complicate, and set that is much more convient than 0.33333... as an example to support his theory. So, RenShengGe lists a lot of numbers in textbooks and starts his great work. To his dissapoint, he soon realizes that the denominator of the fraction may be very big which kills the simplicity that support of his theory. But RenShengGe is famous for his persistence, so he decided to sacrifice some accuracy of fractions. Ok, In his new solution, he confines the denominator in [1,1000] and figure out the least absolute different fractions with the decimal fraction under his restriction. If several fractions satifies the restriction, he chooses the smallest one with simplest formation. InputThe first line contains a number T(no more than 10000) which represents the number of test cases. And there followed T lines, each line contains a finite decimal fraction x that satisfies . OutputFor each test case, transform x in RenShengGe's rule. Sample Input3 Sample Output1/1 |
枚举分母,然后通过相乘得到分子,需通过小数与整数之间差值的逐渐缩小去寻找,,最接近分数。最后还要约分,找最简分数
#include<stdio.h>
#include<string.h>
#include<math.h>
double abs(double a)
{
if(a<=0)
return -a;
else
return a;
}
int gcd(int a,int b)
{
if(a%b==0)
return b;
else
return gcd(b,a%b);
}
int main()
{
double m;
int n;
scanf("%d",&n);
while(n--)
{
scanf("%lf",&m);
double minn=abs(0-m);
int a=0,b=1;
for(int i=1; i<=1000; i++)
{
int sum=(int)(i*m+0.5);//核心逼近分子
if(sum<=i)
{
double f=sum*1.0/i;
double k=abs(f-m);
if(minn>k)//一步步缩小差距,使真实商与被给与的小数差值达到最小
{
minn=k;
a=sum;
b=i;
}
}
}
int r=gcd(a,b);//除最大公约数,约分。。
printf("%d/%d\n",a/r,b/r);
}
}