C++ 这是一个二进制搜索代码,我无法解决这个问题

C++ 这是一个二进制搜索代码,我无法解决这个问题,c++,c++11,C++,C++11,这是我的代码。代码正在运行,但没有得到正确的结果。 对于ex-搜索程序中的3,即使存在,也会得到“未找到”的输出 #include<stdlib.h> #include<iostream> using namespace std; int Bsearch(int arr[],int item,int n) { int low,mid,up; low=0;up=n-1; while(low<=up && item!=arr[mid]) {

这是我的代码。代码正在运行,但没有得到正确的结果。 对于ex-搜索程序中的3,即使存在,也会得到“未找到”的输出

 #include<stdlib.h>
 #include<iostream>
using namespace std;
int Bsearch(int arr[],int item,int n)
{
 int low,mid,up;
 low=0;up=n-1;
 while(low<=up && item!=arr[mid])
 {
     mid=(low+up)/2;
     if(item==arr[mid])
        return mid;
     else if(item<arr[mid])
        low=mid+1;
     else
        up=mid-1;
 }
 return -1;


}
int main()
{
    int index,item;;
    int arr[]={1,2,3,4,5,6,7,8,9};

  cout<<"enter search item\n";
  cin>>item;
    index=Bsearch(arr,item,9);
    if(index!=-1)
    cout<<"element found at position"<<(index+1);
    else
    cout<<"element not found";

    return 0;
}
#包括
#包括
使用名称空间std;
int b搜索(int arr[],int item,int n)
{
int低、中、高;
低=0;高=n-1;
而(低问题在于:

if(item==arr[mid])
        return mid;
     else if(item<arr[mid])
        low=mid+1;
     else
        up=mid-1;
或者更改此条件
否则(项目arr[mid])
代码将正常工作

if(item==arr[mid])
        return mid;
     else if(item > arr[mid])
        low=mid+1;
     else
        up=mid-1;

注意:
while(low)您是否尝试过使用调试器或输入一些打印来查看发生了什么?此网站的设计目的并不是帮助您查找错误。您还使用了
mid
,在它被赋值之前,会导致未定义的行为。(另外,
和&item!=arr[mid]
while测试的一部分是不必要的。)@1201programalm谢谢你的评论。@1201programalm是的,正确!
if(item==arr[mid])
        return mid;
     else if(item > arr[mid])
        low=mid+1;
     else
        up=mid-1;