为什么此代码是同一操作的2倍

Why this code is executing 2 times the same operation?

本文关键字:操作 2倍 代码 为什么      更新时间:2023-10-16

所以我有一个基本猜测数字 game。

在我的int main中,我有三个函数用于播放它。我有一个围绕这些功能的游戏循环,带有bool = falsereturn value集等于我的Playagain功能。

一切效果很好,但是当您猜到正确的数字时,它询问您是否要出于某种原因再次玩两次。

我尝试删除我在 main中调用函数的实例之一:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include<string>

void PrintIntro();
void PlayGame();
bool PlayAgain();
int main() {
    bool bPlayAgain = false;
    do {
        PrintIntro();
        PlayGame();
        PlayAgain();     //I've tried removing this line
        bPlayAgain = PlayAgain(); //I've also played around with this one
    } while (bPlayAgain);
    return (0);
}
void PrintIntro()
{
    std::cout << "Guess a number between 1-100, fool!n";
}
void PlayGame()
{
    srand(static_cast<unsigned int> (time(0)));
    int HiddenNumber = rand();
    int Number = (HiddenNumber % 100) + 1;
    int Guess;
    do {
        std::cin >> Guess;
        if (Guess > Number) {
            std::cout << "You are too high bro!nn";
        }
        else if (Guess < Number) {
            std::cout << "You need to get higher bro!nn";
        }
        else if (Guess = Number) {
            std::cout << "You are just high enough, you win!nn";
        }
    } while (Guess != Number);
}
bool PlayAgain()
{
    std::string Response = "";
    std::cout << "Would you like to play again? yes or no." << std::endl;
    std::getline(std::cin, Response);
    std::cout << std::endl;
    return (Response[0] == 'y') || (Response[0] == 'Y');
}

这是修复的代码。我添加了一个名为Game的新布尔功能,它可以玩游戏,如果玩家想重新玩游戏,则返回True。

#include <iostream>
#include <cstdlib>
#include <ctime>
#include<string>

void PrintIntro();
void PlayGame();
bool PlayAgain();
bool Game();
int main() {
    bool bPlayAgain = Game();
    while(bPlayAgain == true)
    {
        bPlayAgain = Game();
    }
    return (0);
}
void PrintIntro()
{
    std::cout << "Guess a number between 1-100, fool!n";
}
void PlayGame()
{
    srand(static_cast<unsigned int> (time(0)));
    int HiddenNumber = rand();
    int Number = (HiddenNumber % 100) + 1;
    int Guess;
    do {
        std::cin >> Guess;
        if (Guess > Number) {
            std::cout << "You are too high bro!nn";
        }
        else if (Guess < Number) {
            std::cout << "You need to get higher bro!nn";
        }
        else if (Guess = Number) {
            std::cout << "You are just high enough, you win!nn";
        }
    } while (Guess != Number);
}
bool PlayAgain()
{
    char Response;
    std::cout << "Would you like to play again? yes or no." << std::endl;
    std::cin >> Response;
    std::cout << std::endl;
    return (Response == 'y') || (Response == 'Y');
}
bool Game()
{
    PrintIntro();
    PlayGame();
    bool selection = PlayAgain();
    return selection;
}