CS50 pset3 find总是返回true

时间:2017-03-01 21:32:19

标签: 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 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&lt; values [mid + 1]&amp;&amp; value&gt; values [mid -1]”返回false但无效,所以我从这里的代码中省略了它们。非常感谢任何帮助。

干杯

汤姆

1 个答案:

答案 0 :(得分:0)

我还没有检查过你的代码的逻辑,但是你不能设置一个函数来返回一个bool但是也用它来返回数字,如同     return min = mid + 1; 或者在     return max = mid - 1;

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

此外,C不具有布尔类型,除非您在代码中定义它们或导入stdbool.h

编辑:只记得您无法更改函数的签名,因此请尝试创建自己的函数,然后在已定义的搜索函数中调用它。