1 #include <iostream> 2 #include <cmath> //wo de 编译器里的这个abs的功能不能用啊! 3 using namespace std; 4 int main() 5 { 6 double a; 7 double per;//误差计数器; 8 int son_num;//代表分子的枚举; 9 int length;//范围; 10 int mother_num;//分母的枚举; 11 int s;//保存当前误差最小的那个分子; 12 int m;//保存当前误差最小的那组分母; 13 double item;//保存分母的浮点型 14 cin>>a; 15 cin>>length; 16 per=length;//第一次把误差设置的很大; 17 for(son_num = 1;son_num <= length;son_num++) 18 { 19 if (per < 1E-14)//忽略精度;因为要求的精度已经达到了,所以以后就不必在改变 已经算好的分子和分母了! 20 per = 0; 21 item = a*son_num;// 22 mother_num = int(item+0.5);//四舍五入。把最接近的那个整数找出来! 23 if (mother_num == 0)//临界状态 24 mother_num = 1; 25 if (mother_num > length)// 26 mother_num = length; 27 if (per > abs(a-(double)mother_num/double(son_num)))//始终保存的是最小误差的那组; 28 { 29 per = abs(a-(double)mother_num/double(son_num)); 30 m = mother_num; 31 s = son_num; 32 } 33 } 34 cout<<m<<' '<<s<<endl;// 35 }
关注我的公众号,当然,如果你对Java, Scala, Python等技术经验,以及编程日记,感兴趣的话。
技术网站地址: vmfor.com