输出和返回值区别

  • Post author:
  • Post category:其他


写了一段代码递归二分查找,如下:

#include <iostream>

using namespace std;

int BinarySearch(int a[], int x, int left,int right)
{

    int mid = (left+right)/2;
    if(x == a[mid])
    {
        return mid;
    }
    if (x < a[mid])
    {   right = mid-1;
        BinarySearch(a,x,left,right);
    }
    else
    {   left = mid+1;
        BinarySearch(a,x,left,right);
    }
    return -1;
}

int main()
{
    int x=5;
    int left = 0;
    int right = 9;
    int a[] = {0,1,2,3,4,5,6,7,8,9};
    BinarySearch(a,x,left,right);

}

别人给的demo,然后我以为return返回其值,但是运行之后没有发现返回内容,单步调查发现return没有返回值,百度之后,修改为:

#include <iostream>

using namespace std;

int BinarySearch(int a[], int x, int left,int right)
{

    int mid = (left+right)/2;
    if(x == a[mid])
    {
        cout << mid;
        return 0;
    }
    if (x < a[mid])
    {   right = mid-1;
        BinarySearch(a,x,left,right);
    }
    else
    {   left = mid+1;
        BinarySearch(a,x,left,right);
    }
    return -1;
}

int main()
{
    int x=5;
    int left = 0;
    int right = 9;
    int a[] = {0,1,2,3,4,5,6,7,8,9};
    BinarySearch(a,x,left,right);

}

搜网上答案被嘲讽了

return 是方法的返回值,是将方法的执行结果返回给调用方的一个关键字;
cout是一个静态的方法,作用是向命令行输出。



版权声明:本文为qq_30170949原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。