【问题标题】:CS50 pset3 find always returns trueCS50 pset3 find 总是返回 true
【发布时间】:2017-03-01 21:32:18
【问题描述】:

所以我一直在努力解决这个问题,现在需要一些关于布尔函数的帮助。我被困在 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 values[mid -1]" 以返回 false 但无济于事,所以我从代码在这里。任何帮助将不胜感激。

干杯

汤姆

【问题讨论】:

    标签: search find helpers cs50


    【解决方案1】:

    我没有检查你的代码的逻辑,但你不能设置一个函数来返回一个布尔值,但也可以使用它来返回数字,如 返回最小值 = 中间 + 1; 或在 返回最大值 = 中 - 1;

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

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

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

    【讨论】:

    • 你发现我正试图返回我的新最小值和最大值,对于任何值都返回 true。应该已经发现,对于所有情况,它都返回了真正的错误,因为我使用了 return。感谢您的帮助。
    猜你喜欢
    • 2020-09-04
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2017-05-10
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多