Search CS50 pset3查找始终返回true
所以我一直在努力解决这个问题,现在需要一些bool函数的帮助。我被困在pset3中助手的搜索部分 我知道我的选择排序功能可以工作,因为我使用printf检查正在排序的数字,我用一个简单的线性搜索测试find,以确认它工作正常 我的搜索功能代码如下:Search CS50 pset3查找始终返回true,search,find,helpers,cs50,Search,Find,Helpers,Cs50,所以我一直在努力解决这个问题,现在需要一些bool函数的帮助。我被困在pset3中助手的搜索部分 我知道我的选择排序功能可以工作,因为我使用printf检查正在排序的数字,我用一个简单的线性搜索测试find,以确认它工作正常 我的搜索功能代码如下: bool search(int value, int values[], int n) { // Set upper and lower limits for mid point calculation int max = n - 1; int
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;
bool搜索(int值,int值[],int n)
{
//设置中点计算的上限和下限
int max=n-1;
int min=0;
while(最小值[中间])
返回最小值=中间值+1;
//相同的原理,但适用于阵列的左半部分
else if(值<值[mid])
返回最大值=中间值-1;
}
返回false;
}
据我所知,我的逻辑对于实际计算是合理的。我已经尝试过许多不同的返回false的方法,比如“if(valueTom我没有检查代码的逻辑,但是您不能设置一个函数来返回bool,而是使用它来返回数字,如中所示 返回最小值=中间值+1; 或者 返回最大值=中间值-1 只需将函数设置为返回int,并使用1和0作为true和false 此外,C没有布尔类型,除非您在代码中定义它们或导入stdbool.h
编辑:刚刚记住,您不能更改函数的签名,因此请尝试创建一个自己的函数,然后在已定义的搜索函数中调用它。您注意到了,我正在尝试返回新的最小值和最大值,对于任何值,该值都返回真值。应该已经发现,在所有情况下,它都返回真值错误在于我使用了return。谢谢你的帮助。