c++ - 递归函数总是返回假

标签 c++ recursion

我的递归程序在达到指定目标时没有返回 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/

相关文章:

c++ - 这个数组初始化是如何发生的?

c++ - 复制模板化 vector

c++ - 将 .exe 嵌入普通文件

java - 在二叉树的节点类中递归

Java 递归通用模板 : what does this mean by . .. S extends Writer<E>> extends Entity<E,S>

python - 如何从 kivy/python 中的小部件树中获取所有小部件的列表。递归函数没有按预期工作

c++ - 多小类分布

c++ - std::make_unique<T> 与重置(新 T)

c - 返回字符串中包含子字符串的第一个索引的递归函数

Javascript - 迭代深层嵌套对象并更改某些未知值