【发布时间】:2018-08-02 22:12:18
【问题描述】:
我正在使用递归进行作业。我似乎无法弄清楚为什么当数字不在数组中时我的函数不会返回 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);
}
}
【问题讨论】:
-
else if ((arr[S] == 0) ...应该是else if ( (S == 0) ...??到目前为止,您正在查看数组的值,而不是索引。 -
听起来您可能需要学习如何使用调试器来单步调试您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。延伸阅读:How to debug small programs
-
S是大小,arr[S]超出边界。 -
arr[S]访问越界数据,因为S是数组的大小,最后一个索引是S - 1。 -
found变量的意义何在?为什么不return true;和return false;。保持简单!