算法查找结果并测试为true但不返回de值并返回-2。有人知道为什么吗?我无法弄明白。 这是代码:
int recursiveBinarySearch(int* a, int p, int r, int x){
if(p>r){
return -1;
}else{
int m = (p+r)/2;
cout<<(a[m]==x)<<endl;
if(a[m]==x){
cout<<"entering"<<endl;
return (m+1);
cout<<"wtf?"<<endl;
}else if(x<a[m]){
recursiveBinarySearch(a,p,m-1,x);
}else if(x>a[m]) recursiveBinarySearch(a,m+1, r,x);
}
return -2;
}
这是输出($:=我的输入):
>>$./a.out
>>Type the number of slots
>>$100
>>Type a number to search for
>>$40
>>0
>>0
>>0
>>0
>>0
>>1
>>entering
>>The search did not return any item-2
答案 0 :(得分:2)
在递归尝试写入时忽略recursiveBinarySearch
的返回值:
return recursiveBinarySearch(a,p,m-1,x);
答案 1 :(得分:1)
当你递归调用recursiveBinarySearch( )
时,用return
语句调用它,因为如果递归函数返回一些东西,调用递归函数的函数应该返回相同的值。
代码应为:
int recursiveBinarySearch(int* a, int p, int r, int x)
{
if(p>r)
return -1;
else
{
int m = (p+r)/2;
cout<<(a[m]==x)<<endl;
if(a[m]==x)
{
cout<<"entering"<<endl;
return (m+1);
cout<<"wtf?"<<endl;
}
else if(x<a[m])
//Added a return statement to both the recurring function call.
return recursiveBinarySearch(a,p,m-1,x);
else if(x>a[m])
//Added a return statement to both the recurring function call.
return recursiveBinarySearch(a,m+1, r,x);
}
return -2;
}