我的递归程序在达到指定目标时没有返回 true,即使它看起来应该如此。它只是返回 false,然后终止,我不明白为什么。
我尝试以各种可能的方式重新排列 If/Else 语句的顺序,我尝试使用 cout 对其进行调试,看起来它应该返回 true,但实际上并没有。
#include <iostream>
using namespace std;
bool isNumberInArray(const int anArray[], int first, int last, int targetNum) {
if (first > last) { //if last number is less than the first number to be searched
return false; //Returns false if the size of the array to be searched is less than the first element of the array
}
if (anArray[last] == targetNum) { //if number at "last" position is equal to the target
return true; //Returns true if the target is found at the last position
}
else { //run again, with last = last - 1
cout << "searching for " << targetNum << "; ran else; position " << last << " value " << anArray[last] << "\n";
//previous line used for testing purposes
isNumberInArray(anArray, first, (last - 1), targetNum);
}
}
int main() {
int numberArray[10] = {1, 2, 3, 11, 5, 6, 7, 8, 9, 10};
if (isNumberInArray(numberArray, 0, 9, 11t))
cout << "True\n";
else
cout << "False\n";
return 0;
}
当last的值到达targetNum所在的位置时,程序实际上应该返回“true”,但它总是返回false,即使它是true,我也想不通为什么。我放在函数中的 cout 语句甚至在程序到达 targetNum 时停止,但它仍然返回 false:
搜索 11;跑别的;位置9值10
搜索 11;跑别的;位置8值9
搜索 11;跑别的;位置7值8
搜索 11;跑别的;位置6值7
搜索 11;跑别的;位置5值6
搜索 11;跑别的;位置4值5
错误
11 在第 3 位。
最佳答案
您需要在 else 子句中返回递归调用的结果。
else { //run again, with last = last - 1
cout << "searching for " << targetNum << "; ran else; position " << last << " value " << anArray[last] << "\n";
//previous line used for testing purposes
return isNumberInArray(anArray, first, (last - 1), targetNum);
}
如果您查询的第一项是您要查找的内容,它将返回 true,但是,它永远不会检查对 isNumberInArray() 的进一步调用,因为您永远不会检查该值。当程序最终返回到第一次调用时,它将输入 if (first > last) 并返回 false,而实际上它应该从 isNumberInArray 返回值。
关于c++ - 递归函数总是返回假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58161051/