求指点:用C++取值的算法!
问题:假如我有一组数,例{1,2,3,4,5,6……},我想输入一个数,假如是2.3,然后输出是是数组里与它最靠近的那个数即“2”。
想法:用输入数2.3与每一个数做减法得到最小差值的绝对值,然后在检测那一个数与最小绝对差值的和或差等于输入值,最后输出这个值!这个想法太复杂了有没有更优化的算法,求指点!

程序代码:a = 2.3 - 2;
b = 3 - 2.3;
if(a > b)
cout << b << endl;
else cout << a << endl;
程序代码:#include <iostream>
double binsch( double k);
using namespace std;
int main()
{
cout<<"enter you number:"<<endl;
double value_p;
cin>>value_p;
binsch(value_p);
cout<<binsch(value_p)<<endl;
}
#define SIZE 10
int g_x[SIZE] = {1 ,2 ,3 ,4 ,5, 6 ,7 ,8, 9, 10};
double binsch( double k)
{
int low=0,high=SIZE-1;
while (low<=high)
{
int mid=(low+high)/2;
if (k==g_x[mid] )
return g_x[mid];
else if(k<g_x[mid] )
high=mid-1;
else low=mid+1;
}
return -1; // 返回-1
}