所以我有一个基本的猜数字游戏。
在我的 int main
中,我有三个用于播放它的函数。我有一个围绕这些函数的游戏循环,其中 bool = false
和 返回值
设置等于我的 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!\n\n";
}
else if (Guess < Number) {
std::cout << "You need to get higher bro!\n\n";
}
else if (Guess = Number) {
std::cout << "You are just high enough, you win!\n\n";
}
} 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 的新 boolean 函数,用于玩游戏,如果玩家想重新玩则返回 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!\n\n";
}
else if (Guess < Number) {
std::cout << "You need to get higher bro!\n\n";
}
else if (Guess = Number) {
std::cout << "You are just high enough, you win!\n\n";
}
} 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;
}
关于c++ - 为什么这段代码执行两次相同的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55958873/