C++ 递归函数总是返回False
我的递归程序在到达指定目标时不会返回true,即使它看起来应该返回true。它只是返回false,然后终止,我不知道为什么 我尝试以各种可能的方式重新排列If/Else语句的顺序,我尝试使用cout对其进行调试,它看起来应该返回true,但没有C++ 递归函数总是返回False,c++,recursion,C++,Recursion,我的递归程序在到达指定目标时不会返回true,即使它看起来应该返回true。它只是返回false,然后终止,我不知道为什么 我尝试以各种可能的方式重新排列If/Else语句的顺序,我尝试使用cout对其进行调试,它看起来应该返回true,但没有 #include <iostream> using namespace std; bool isNumberInArray(const int anArray[], int first, int last, int targetNum) {
#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;
}
#包括
使用名称空间std;
bool isNumberInArray(const int anArray[],int first,int last,int targetNum){
if(first>last){//if last number小于要搜索的第一个数字
return false;//如果要搜索的数组的大小小于数组的第一个元素,则返回false
}
if(anArray[last]==targetNum){//“last”位置的数字等于目标
return true;//如果在最后一个位置找到目标,则返回true
}
else{//再次运行,last=last-1
cout您需要在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);
}
else{//再次运行,last=last-1
在isNumberArray
的最后一个else
中,您是否缺少return
。您递归调用isNumberArray
,但实际上并没有查询该调用的返回值。事实上,您的程序通过到达非void
函数的结尾而显示出未定义的行为调用return
语句。在“if(IsNumberArray(numberArray,0,9,11t))”中,可能最后的“t”是一个输入错误。这会导致“错误:找不到数值文本运算符“运算符”“t”