第四章第7题:确定包围一个点两条线段。
这个问题与给定一个数,在数组中找到最接近这个数的两个数是一样的,采用二分搜索实现:
#include<iostream>
using namespace std;
void find_approximate(int a[],int N,float x,int& low,int& high)//在数组a中找到最接近x的两个数,下标存于low和high中
{
int L=0,H=N-1;
int M=0;
while (L<H-1)
{
M=(L+H)/2;
if (x==a[M])
{
low=M;
high=M;
cout<<"x="<<x<<" is just on the point "<<"a["<<M<<"]="<<a[M]<<endl;
return;
}
else if (x<a[M])
{
H=M;
}
else
{
L=M;
}
}
if (a[H]==x)
{
cout<<"x="<<x<<" is just on the point "<<"a["<<H<<"]="<<a[H]<<endl;
low=H;
high=H;
}
else if (a[L]==x)
{
cout<<"x="<<x<<" is just on the point "<<"a["<<L<<"]="<<a[L]<<endl;
low=L;
high=H;
}
else if (a[H]>x&&a[L]<x)
{
low=L;
high=H;
cout<<"x="<<x<<" is between the point "<<"a["<<L<<"]="<<a[L]<<" and "<<"a["<<H<<"]="<<a[H]<<endl;
}
else
cout<<"x="<<x<<" is not in this interval!"<<endl;
}
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,10};
int low=0,high=0;
find_approximate(a,sizeof a/sizeof(a[0]),1.1,low,high);
}