为什么此代码是同一操作的2倍
Why this code is executing 2 times the same operation?
所以我有一个基本猜测数字 game。
在我的int main
中,我有三个函数用于播放它。我有一个围绕这些功能的游戏循环,带有bool = false
和return 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;
}
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 对字符串进行位操作
- 我想知道长双倍和双倍之间的区别
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 按值 C++ 返回时进行双倍移动
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 是新的(&*p)双倍;一个无操作。因此,uninitialized_default_construct是否也变得无操作?
- 为什么此代码是同一操作的2倍
- FlasCC:Vector 之间的互操作。<Number> 和双倍[]