#include <iostream>
#include <random>
#include <limits>
namespace random
{
std::random_device rd;
std::seed_seq rr = {rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()};
std::mt19937 mt{rr};
int get(int min, int max)
{
std::uniform_int_distribution uid{min, max};
return uid(mt);
}
} // namespace random
int getGuess(int i)
{
while (true)
{
std::cout << "Guess #" << i << ":";
int guess{};
std::cin >> guess;
if (!std::cin || guess < 1 || guess > 100)
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Please enter the correct number!" << '\n';
continue;
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return guess;
}
}
bool playGame(int guesses, int random)
{
std::cout << "Let's play a game. I'm thinking of a number between 1 and 100. You have " << guesses << " tries to guess what it is. " << '\n';
for (int i{1}; i <= guesses; i++)
{
int guess{getGuess(i)};
if (random > guess)
std::cout << "Your guess is too low." << '\n';
else if (random < guess)
std::cout << "Your guess is too high." << '\n';
else // random == guess
return true;
}
return false;
}
bool playAgain()
{
while (true)
{
std::cout << "Would you like to play again (y/n)? ";
char ch{};
std::cin >> ch;
switch (ch)
{
case 'y':
return true;
case 'n':
return false;
default:
std::cout << "Please enter the correct option!" << '\n';
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
}
int main()
{
do
{
constexpr int guesses{7};
int num{random::get(1, 100)};
bool won{playGame(guesses, num)};
if (won)
{
std::cout << "Correct! You win!" << '\n';
}
else
{
std::cout << "Sorry, you lose. The correct number was " << num << "\n";
}
} while (playAgain());
return 0;
}
原文链接: https://www.cnblogs.com/leafz/p/17130850.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/318690
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!