使用递归

时间:2016-10-01 00:13:07

标签: c++ recursion

我无法理解递归。我正在寻找一些反馈,看看这个程序看起来如何。

问题::: 编写一个名为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);
}

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

在您的示例中,您只提供了一个条件停止。为了使其正常工作,请尝试以下方法:

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);
}