我正在用10个元素的数组编写一个简单的二进制搜索程序。这是我的代码;
int main(int argc, char *argv[]) {
int query, pos;
int A[10] = {0,1,2,3,4,5,6,7,8,9}; //contents of the array
cout<<"enter query = ";
cin>>query;
int x=(10-1)/2; //the middle ground
bool found = false;
if(query<A[x]){ //if query is less than A[x] search before i
for(int i=0;i<=x;i++){
if(A[i]==query){
found=true;
pos=i;
}
}
}
if(query>A[x]){
for(int i=4;i<10;i++){
if(A[i]==query){
found=true;
pos=i;
}
}
}
if (found=false){
cout<<"NOT FOUND"<<endl;
}
else{
cout<<"FOUND AT A["<<pos<<"]"<<endl;
}
return 0;
}
奇怪的是,如果我尝试搜索不存在的元素,它会返回FOUND AT A [48092]或其他内容。我哪里做错了?
答案 0 :(得分:1)
你看到的数字是变量pos的值,你看到的原因是因为拼写错误:
if (found=false)
应该是
if (found == false)