布尔递归函数总是返回真

用户5125729

我正在使用递归进行作业。当数字不在数组中时,我似乎无法弄清楚为什么我的函数不会返回 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试图将arrat的值S与 0进行比较,而不是测试您的索引变量现在是否为 0,我建议的代码就是这样做的。

但这也可能解释了为什么该函数总是返回 true,尽管存在未定义的行为并且程序没有崩溃。因为您的函数没有适当终止,它会不断调用isMember(...,S-1,...). 因此,它将不断减少索引并更改arr[S]访问的内存位置这个过程会一直持续下去,直到它找到arr[S] == 0或找到你正在寻找的价值。碰巧的是,在遇到 0 之前,您在内存中某处遇到了目标值。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章