我正在用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 A48092或其他东西。我哪里错了?
发布于 2014-12-10 23:05:09
您看到的数字是变量pos的值,您看到它的原因是因为输入错误:
if (found=false)应该是
if (found == false)https://stackoverflow.com/questions/27404085
复制相似问题