c++ 二分查找问题

代码如下:
#include<iostream>
using namespace std;
#define NUM 10
int swap(int [],int,int,int);
int main()
{
int arry[NUM]={2,4,6,8,10,12,14,16,18,20};
int key;
cout<<"please input key"<<endl;
cin>>key;
int x=swap(arry,0,NUM,key);
if(x=-1)
cout<<"there is nothing!"<<endl;
else
cout<<""<<x<<endl;
return 0;

}

int swap(int a[],int low,int high,int searchkey)
{
int middle;
while(low<high)
{
middle=(high+low)/2;
if(searchkey<a[middle])
high=middle-1;
else if(searchkey>a[middle])
low=middle+1;
else
return middle;
}

return -1;
}

无论输入什么,都 返回 -1 输出“there is nothing”

粗心了吧?!赋值和等号易写错!
int main()
{
int arry[NUM]={2,4,6,8,10,12,14,16,18,20};
int key;
cout<<"please input key"<<endl;
cin>>key;
int x=swap(arry,0,NUM,key);
if(x==-1) // 如果是赋值,恒成立,自然执行下面的语句
cout<<"there is nothing!"<<endl;
else
cout<<""<<x<<endl;
return 0;
}
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答