【问题标题】:A member test using Recursion使用递归的成员测试
【发布时间】:2016-10-01 00:13:07
【问题描述】:

我无法理解递归。我在这里寻找一些反馈,看看这个程序的外观。

问题 ::: 编写一个名为 isMember 的递归布尔函数。该函数应该接受三个参数:一个整数数组、一个表示数组中元素数量的整数和一个要搜索的整数值。如果在数组中找到该值,则该函数应返回 true,如果未找到该值,则该函数应返回 false。演示在要求用户输入数字数组和要搜索的值的程序中使用该函数。

我有什么::

   #include <iostream>

using namespace std;

bool isMember(int[],int,int);


int main()
{
    const int SIZE = 10;
    int numSearch;
    int elementz[SIZE];

    for(int i = 0; i < SIZE; i++)
    {
        cout << "Element " << i + 1 << "\t";
        cin >> elementz[i];
    }

    cout << "Enter element to search\n";
    cin >> numSearch;

    bool value = isMember(elementz,SIZE,numSearch);

    if(value ==1)
        cout << "Element is found\n";
    else
        cout << "Element not found\n";

    return 0;
}


bool isMember(int arr[], int sizze, int num)
{
    if(arr[sizze] == num)
        return true;
    else
        isMember(arr,sizze -1, num);
}

【问题讨论】:

  • 您的 isMember 函数需要一个错误的案例(当 sizze 为 -1 时)。除此之外 - 是的,它是一个递归函数。它应该返回 isMember(arr, sizze - 1, num) 而不是仅仅调用 isMember(arr, sizze - 1, num) 以便返回值可以在调用堆栈中向上移动到原始调用函数。

标签: c++ recursion


【解决方案1】:

如果if 子句为假,您的函数不会返回。另外,请记住,索引从 0 开始,而不是 1(为什么是 sizze?)。

我建议从 3 个值的数组开始,而不是 10 个。这样您就可以手动跟踪和展开连续调用。

【讨论】:

    【解决方案2】:

    为了使递归起作用,您不仅需要“条件停止”,还需要无条件停止。

    在您的示例中,您只提供了有条件的停止。要使其正常工作,请尝试以下操作:

    bool isMember(int arr[], int sizze, int num)
    {
        if ( sizze < 0 )  // "inconditional stop"
            return false;
    
        if(arr[sizze] == num)  // conditional stop. It could happen or not
            return true;
        else
            isMember(arr,sizze -1, num);
    }
    

    【讨论】:

    • 好的,谢谢。还有一个快速的问题。会不会出现找不到Element的情况?
    • 这取决于你如何填充你的数组
    猜你喜欢
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 2020-08-29
    • 2019-09-30
    • 2014-07-09
    相关资源
    最近更新 更多