我的递归程序在到达指定目标时不会返回 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 返回值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句