一个计算近似即约分数的题目,解法是枚举分母。地址:http://acm.pku.edu.cn/JudgeOnline/problem?id=1650

#include  < iostream >
#include 
< cmath >
using namespace std;

int  main()
{
    
int l,d,n,ansd,ansn;
    
double a,min=100000000;
    
while ( scanf("%lf%d",&a,&l) != EOF )
    
{
        ansd
=ansn=1;
        
for(n=1;n<=l;n++)
        
{
            d
=(int) n/a;
            
if (d>l) continue;
            
if (fabs(a-n*1.0/d)<min)
            
{
                ansn
=n;
                ansd
=d;
                min
=fabs(a-n*1.0/d);
            }

            d
++;
            
if (d>l) continue;
            
if (fabs(a-n*1.0/d)<min)
            
{
                ansn
=n;
                ansd
=d;
                min
=fabs(a-n*1.0/d);
            }
    
        }

        printf(
"%d %d\n",ansn,ansd);
    }

return 0;
}