c++ - C++ 中的递归 boolean 函数

标签 c++ recursion boolean

我是 C++ 的新手(大部分情况下是一般编程),我正在参加一个在线类(class),接下来是教学,目的是构建一个游戏。在其中一个控制台应用程序项目中,我们必须编写代码询问用户是否想再次玩游戏。该部分程序的目标是要求用户仅通过键入“y”或“n”来回复如果用户通过做其他事情来回应,则重新提出问题。

我已经尝试编写执行此操作的代码,据我所知,代码工作正常。我的问题是,我编写的代码在以下意义上是否有效:

  1. 代码能否成功完成概述的任务?
  2. 如果以后增长,这样的代码是否容易出现更多错误?

我的代码如下。在 main 函数中:

.
.
.
do
{
    PlayGame();
}
while (AskToPlayAgain());

AskToPlayAgain 的函数定义以及恰当的描述:

bool AskToPlayAgain()
{
 bool Play = true;
 string response = "";
 cout << "Would you like to play again? y/n... ";
 getline(cin, response);

 if (response == "y") { }

 else if (response != "n")
 {
     cout << "Please enter a valid response." << endl;
     // We want AskToPlayAgain called again to ask for a proper response again; however,
     // just calling it outside a conditional will cause the current "Play" value to be returned.
     // This value is true by default and this function will return it even if "n" is entered after
     // an invalid response. As such, in this case, we want this function to be called in the event
     // of an invalid response which will always happen and we don't want the return value of the nested
     // AskToPlayAgain function to be returned, which is true by default unless the program has successfully exited.
     // Furthermore, once the nested AskToPlayAgain returns false, we want the program to exit and not return the "Play"
     // (which is set to true) by the higher level AskToPlayAgain.

     if (AskToPlayAgain()) { }
     else { return false; }
 }

 else
 {
     Play = false;
     cout << "Thank you for playing! :D" << endl;
 }

 return Play;
}

我在代码注释中提出的推理是否有效?有没有失败的测试用例?我已经尝试了一些测试用例,但它们都有效。

非常感谢您对此提供的任何帮助!

最佳答案

您的递归方法没有任何问题,但您可以使用循环来简化它,并避免与递归相关的潜在问题。循环和递归密切相关。 if (response == "y") { } 没有错,但这是一种奇怪的编程习惯。如果您在达到此条件后不打算做任何事情,那么请不要为它进行测试。

另一种使用 while 循环的方法:

bool AskToPlayAgain()
{
    while(true)
    {
        string response;
        cout << "Would you like to play again? y/n... ";
        getline(cin, response);

        if(response == "y")
        {
            return true;
        }
        else if(response == "n")
        {
            cout << "Thank you for playing! :D" << endl;
            return false;
        }

        cout << "Please enter a valid response." << endl;
    }
}


编辑

递归函数的另一个例子:

这次我们添加一个counter值来演示。

如果您运行此程序并继续提供无效输入,则 counter 将上升。它显示递归函数需要如何等待所有其他递归函数完成。

我添加了未使用的 char buf[1000]。它的目的就是制造问题!

潜在问题:每个函数需要分配1000字节栈内存(加上函数中其他栈变量的内存,以及std::string的堆内存)。在函数存在之前,此内存不会被释放,因此它会累积。您的程序中的堆栈限制为几兆字节,因此现在存在潜在的堆栈溢出错误。

bool AskToPlayAgain(int counter)
{
    char buf[1000]; //<-- allocate lots of stack memory to cause problems!
    cout << "counter start: " << counter << " - memory allocated\n";

    cout << "play again? y/n... ";
    string response;
    getline(cin, response);

    if(response == "y")
    {
        return true;
    }
    else if(response == "n")
    {
        cout << "Thank you for playing! :D\n";
        return false;
    }

    cout << "invalid response\n";
    bool result = AskToPlayAgain(counter + 1);

    cout << "counter: " << counter << " - memory cleanup\n";
    return result;
}

int main()
{
    do
    {
        printf("play...\n");
    } while(AskToPlayAgain(1));
    return 0;
}

因此,最好使用循环来支持递归函数。但话又说回来,递归函数有时很有用,如果内存分配在控制之下(就像在你的例子中)并且有明确的路径来打破递归,那么继续使用它。

关于c++ - C++ 中的递归 boolean 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48312947/

相关文章:

python - 在 python 类中存储和检查 boolean 值

c++ - std::fstream 不创建文件

c++ - 模板名和类模板名的区别

c++ - 为什么这个递归调用以这种方式工作?

python - 在 python 中返回 1 而不是 true

javascript - boolean 逻辑,如果 4 中 1 为 true,则为 true

c++ - C++ std::string 堆内存分配的保证?

c++ - 在打印类似于 "%q"的字符时如何避免在 vsprintf_s() 崩溃

python - 使用递归绘制嵌套三角形

c - 递归删除字符串中的重复字符