【发布时间】:2019-09-30 03:05:09
【问题描述】:
我的递归程序在到达指定目标时没有返回 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。
【问题讨论】:
-
您在
isNumberInArray的最后一个else中缺少return。 -
您递归调用
isNumberInArray,但实际上并没有查询该调用的返回值。事实上,您的程序表现出未定义的行为,通过到达非void函数的末尾而不遇到return语句。 -
在“if (isNumberInArray (numberArray, 0, 9, 11t)) 中,最后的 't' 可能是一个错字。这会导致“错误:无法找到数字文字运算符'operator”“t'”