随机产生一个1~1000之间的整数,使用折半查找法找到该数,并且同时显示折半查找的次数。
#include<iostream>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<conio.h>
#include<cmath>
#include <algorithm>
#include<windows.h>
using namespace std;
class test
{
private:
int n;
public:
test()
{
srand(time(NULL));
n=rand()%1000+1;
}
void func()
{
int count=0;
int left=1,right=1000,mid;//定义区间
while(true)
{
mid=(left+right)/2;
if(mid==n) break;
else if(mid>n)
{
count++;
right=mid;
}
else
{
count++;
left=mid;
}
}
cout<<n<<endl;
cout<<"随机数:"<<mid<<endl;
cout<<"次数:"<<count<<endl;
}
};
int main()
{
test t;
t.func();
system("pause");
return 0;
}