Solution to a problem fraction of the closest

Given a positive real number, find the numerator and denominator does not exceed n most simple fraction, given that it is closest to
the real numbers. "Closest" means that the fraction on the number line recently, if the score is not given fractional distance
only, a minimum output molecule.

Ideas: enumeration molecule, calculated denominator.

#include <bits/stdc++.h>
using namespace std;
int n,ans1=1,ans2=1;
double x;
int main(){
	cin>>n>>x;
	for(int i=1;i<=n;i++){
	 	double z=(i*1.0)/x+0.5;
	 	int a=z;
	 	if(fabs((i*1.0)/(a*1.0)-x)<fabs((ans1*1.0)/(ans2*1.0)-x)&&a<=n){
	 		ans1=i;
	 		ans2=a;
	 	}
	}cout<<ans1<<endl;
	cout<<ans2<<endl;
	return 0;
}
Published 72 original articles · won praise 130 · Views 4074

Guess you like

Origin blog.csdn.net/qq_46230164/article/details/105385532