首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >递归函数中的返回语句

递归函数中的返回语句
EN

Stack Overflow用户
提问于 2020-01-21 07:15:52
回答 1查看 41关注 0票数 0

我正在尝试编写一个递归函数,用于在数组中进行线性搜索,它还会返回找到元素的第一个索引。

代码语言:javascript
代码运行次数:0
运行
复制
int linearSearch(int *A, int size, int val)
{
    if(size>0)
    {
        if(*A==val)
        {
            cout<<val<<" is found in the array!";
            return i;
        }
        else
        {
            linearSearch(A+1,size-1,val);
            i++;
        }
    }
    else
    {
        cout<<val<<" is not there in the array!";
        return -1;
    }
}

但是,当我试图捕获main函数中返回的值时,当元素不存在于数组中时,返回size的值而不是-1。我不知道为什么会发生这种情况。

EN

回答 1

Stack Overflow用户

发布于 2020-07-08 21:47:01

尝尝这个。我在代码中添加了一些注释,这样您就可以更好地理解它。

代码语言:javascript
代码运行次数:0
运行
复制
/* i is the initial position. When you are making a call to linearSearch it should be set to 0 */
int linearSearch(int *A, int size, int val, int i)
{
    /* When you reach end of the array and havent found value, then return -1 */
    /* Every recursive function should have an exit condition */
    if(i == size)
        return -1;

    /* when we found a value return the index */
    if (A[i] == val)
        return i;
    else
        /* If not then move to the next value in the array by incrementing index and recurse */
        return linearSearch(A, size, val, i + 1);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59832129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档