布尔递归功能始终返回真实



我正在使用递归进行分配。我似乎无法弄清楚为什么当数字不在数组中时我的函数不会返回false。由于某种原因,在我看来,正在搜索的数字被添加到数组中。如果有人能告诉我我要去哪里,那将不胜感激。

#include "stdafx.h"
#include <iostream>
using namespace std;
bool isMember(int[], const int, int);
int main() {
    const int SIZE = 5;
    int myArr[SIZE];
    int numSearched;
    cout << "Enter 5 numbers to be searched through." << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << "Enter number " << i + 1 << endl;
        cin >> myArr[i];
    }
    cout << "What number do you want to find?" << endl;
    cin >> numSearched;
    if (isMember(myArr, SIZE, numSearched)) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }
    return 0;
}
bool isMember(int arr[], const int S, int search) {
    bool found = false;
    cout << arr[S] << endl;
    if (arr[S] == search) {
        found = true;
        return found;
    }
    else if ((arr[S] == 0) && (arr[0] != search)) {
        return found;
    }
    else {
        return isMember(arr, S - 1, search);
    }
}

许多人指出,您有一个内存访问问题,您正在尝试在数组大小之外访问内存。已经在功能的最高呼叫中,您会导致问题,因为您将SIZE作为数组索引参数。如果SIZE是数组的大小,则arr[SIZE-1]是内存中数组的最后一个元素。arr[SIZE]是超越末端的一个元素。访问超出数组内存足迹的内存会导致不确定的行为,这是不好的。

总的来说,不良索引是一个巨大的问题。但是,即使您解决了上述问题,另一个问题行也在这里,因为您要在S命中0时停止,但您不正确地写了此。

else if ((arr[S] == 0) && (arr[0] != search)) {

您希望这是:

else if (S == 0) {

语句arr[0] != search是多余的,因为上述条件已经对此进行了检查。原始语句arr[S] == 0试图将arr处的CC_8的值比较0,而不是测试您的索引变量现在为0,我的建议代码为0。

,但这也可能解释了为什么尽管行为不确定,并且该程序没有崩溃,但该功能始终返回。由于您的功能无法适当终止,因此它将不断调用isMember(...,S-1,...)。因此,它将继续减少索引并更改访问的arr[S]的内存位置。这个过程将继续进行,直到找到arr[S] == 0或找到您要寻找的值。碰巧的是,您只是偶然遇到了目标值,然后才遇到0。

您将索引号发送给iSmember,该编号从零开始,当您发送5时,将索引号发送到IS成员ARR [5]时。并应该使用该方法

isMember(myArr, SIZE - 1, numSearched)

和您的代码没有结束条件我在S < 0

之后向您的代码添加结束条件,以结束递归
if (S < 0)
    return false;

尝试这个;(

#include <iostream>
using namespace std;
bool isMember(int[], const int, int);
int main() {
    const int SIZE = 5;
    int myArr[SIZE];
    int numSearched;
    cout << "Enter 5 numbers to be searched through." << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << "Enter number " << i + 1 << endl;
        cin >> myArr[i];
    }
    cout << "What number do you want to find?" << endl;
    cin >> numSearched;
    if (isMember(myArr, SIZE - 1, numSearched)) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }
    return 0;
}
bool isMember(int arr[], const int S, int search) {
    if (S < 0)
        return false;
    bool found = false;
    //cout << "index is " << S << "t" <<  arr[S] << endl;
    if (arr[S] == search) {
        found = true;
        return found;
    }
    return isMember(arr, S - 1, search); 
}

错误在递归函数的停止条件下:

else if ((arr[S] == 0) && (arr[0] != search)) {
    return found;
}

您不是在检查索引是第一个,而是为零。您可以尝试这样的事情:

else if (S <= 0) {
    return false;
}

您也不需要检查值以匹配"搜索",因为它在以前的条件上是多余的。您也可以直接返回false。

最新更新