【问题标题】:Recursive Function Always Returns False递归函数总是返回 False
【发布时间】: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'”

标签: c++ recursion


【解决方案1】:

您需要在 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 返回值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多