# The realization of guessing game with C + +

Time：2020-11-24

Guessing game

In programming, the computer first “thinks” a number between 1 and 100 and asks people to guess. If a person guesses correctly, the number of times the person guesses is output on the screen to reflect the “guess” level of the guesser. Otherwise, the computer will give a prompt to tell people whether the number guessed is too large or too small. The maximum number can be guessed 10 times. If the number is not guessed after 10 times, it will stop Stop guessing this time, and then continue to guess the next number. Each time running the program can guess multiple numbers repeatedly until the operator wants to stop.

[thinking question] if the user inputs the data guessed by the user, if the user accidentally enters an illegal character, such as the character a, then the program will run in error. What can be done to avoid such an error? Please write a program to verify the effectiveness of the method.

``````#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void youxi()
{
srand(time(0));
int number = rand() % 100 + 1;

int count = 0;
int a = 0;

while (a != number&&count<10)
{
Cout < < "please guess a number between 1 and 100?";
fflush(stdin);
scanf("%d",&a);
if (!(a>0 && a<100))
{
Cout < < please enter a valid and qualified number! < endl;
}
else
{
count++;
if (a > number)
{
cout << "Wrong!";
cout << "Too high！" << endl;
}
else if (a < number)
{
cout << "Wrong!";
cout << "Too low!" << endl;
}
if (a != number) a = 0;
}
}
if (count == 10)
Cout < < "the game has ended after more than 10 attempts. Come on next time! " << endl;
else
Cout < "right!" < "you used it" < < count < < "times to guess the answer. " << endl;
}
int main()
{
while (1)
{
youxi();
Cout < < "would you like to do it again? Press end;
int a;
cin >> a;
cout << endl;
if (a != 1)break;
}
system("pause");
return 0;
}``````

More interesting classic game implementation topics are also shared with you:

C + + classic games summary

Python classic games summary

Python Tetris game collection

JavaScript classic games are always playing

Java classic games summary

JavaScript classic games summary