2017-03-01 47 views
-1

所以我一直在挣扎着这个旧的票价,而现在需要一些帮助与布尔功能。我被困在pset3的助手的搜索部分。CS50 pset3找到总是返回真

我知道我的选择排序功能的作品,因为我用printf来检查数字正在排序,我测试发现一个简单的线性搜索,以确认它正常工作。

我对搜索功能的代码如下:

bool search(int value, int values[], int n) 

{ 

// Set upper and lower limits for mid point calculation 
int max = n - 1; 
int min = 0; 


while (min <= max) 
{ 
    // Set the mid point of values as half the difference of the upper and lower limit. 
    int mid = (max - min)/ 2; 

    // If the array position we look at for this itteration of mid is equal to the value, return true 
    if (value == values[mid]) 
    return true; 

    // If the mid value is less than our value, look at the right half (+1 as we dont need to look at the mid point again) 
    else if (value > values[mid]) 
    return min = mid + 1; 

    // Same principle but for the left half of the array 
    else if (value < values [mid]) 
    return max = mid - 1; 

} 
return false; 

}

至于我可以告诉我的逻辑是声音的实际计算。我尝试了任何不同的返回false的方法,比如“if(value < values [mid + 1] & & value> values [mid -1]”返回false但无济于事,所以我省略了它们从这里的代码。任何帮助,将不胜感激。

干杯

汤姆

回答

0

我没有检查你的代码的逻辑,但你不能设置一个函数返回一个布尔值,但也用它来返回数字,如 return min = mid + 1; 或 return max = mid-1;

只需将该函数设置为返回int,并将1和0用作true和false。

此外,C没有布尔类型,除非你定义他们在你的代码或进口stdbool.h

编辑:只记得,你不能改变函数的签名,所以尽量创建自己的函数,然后在已定义的搜索函数中调用它。

+0

你当时正在尝试返回我的新的最小值和最大值,这对于任何值都是正确的。应该发现,对于所有情况来说,这是返回真正的亨氏错误是与我使用回报。谢谢您的帮助。 – TomForrest