【问题标题】:warning as Control reaches at the end of a non-void function when implementing binary search在实现二分搜索时,当 Control 到达非 void 函数的末尾时发出警告
【发布时间】:2014-05-21 13:13:04
【问题描述】:

这是我对二分搜索的实现。虽然得到了正确的答案,但当我编译代码时,我收到一条警告,指出“控制到达非 void 函数的末尾”。为什么我会收到此错误?如何纠正? 提前致谢。

#include <iostream>
using namespace std;

int binary1(int myarray[7], int target) 
{
    int low=1, high=sizeof(myarray);
    while(low<=high)
    {
        int mid=low+(high-low)/2;
        if(myarray[mid]==target)
            return mid;
        else if(myarray[mid]<target)
            low=mid+1;
        else
            high=mid-1;
    }
}

int main()
{
    int a[7] ={3,7,12,44,53,76,98};
    int value = binary1(a,53);
    cout<<value<<endl;
    return 0;
}

    标签: c++ binary-search


    【解决方案1】:

    编译器不确定low &lt;= high,因此您的while 循环可能会终止(考虑未找到您要搜索的元素的情况)。在这种情况下,您将在没有 return 语句的情况下到达 binary1 函数的末尾。这是无效的,因为您的函数返回 int

    【讨论】:

    • 我现在该如何克服呢?
    • while 循环结束后在函数末尾返回一些东西。在您的情况下,也许 -1 表示“未找到项目”是一个很好的值。
    • 谢谢。那非常有帮助。
    【解决方案2】:

    如果函数传递了一个容器中不存在的值,它将到达函数的末尾。深入了解函数调用以及如何返回值(对于初学者,请查看this)超出了这个问题的范围,但我们可以说行为取决于实现。 当我使用这些参数 ({3,7,12,44,53,76,98},1) 调用您的函数时,您的代码在 ideone 上返回 0。

    您应该返回一个值,以防在容器中实际存在元素时无法获得该值。 -1 应该做。

    我会这样写函数:

    int binary1(int myarray[7], int target) 
    {
        int low=1, high=sizeof(myarray);
        int idx = -1;
        while(low<=high)
        {
            int mid=low+(high-low)/2;
            if(myarray[mid]==target){
                idx = mid;
                break;  // answer already found.
              }
            else if(myarray[mid]<target)
                low=mid+1;
            else
                high=mid-1;
        }
      return idx;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-11
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 2015-04-16
      • 1970-01-01
      相关资源
      最近更新 更多