《编程珠玑》 个人实现部分课后答案

第四章第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);
	
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值