c entry loop, guess the number game

Guess the number game

1. Generate random numbers.
2. Control the range of random number generation.
3. Use the loop to judge the input number and the correct number.
If the input number is less than the correct number, the output is too small.

Cycle judgment

When the player chooses to play, he can continue to play. When he chooses to quit, he exits the program. When he enters other numbers, he loops again, so while(input), when input=0, it is false to stop the loop.
Insert picture description here
Menu printing
Insert picture description here

Generate random numbers

The rand() function
Insert picture description here
generates a random number from 0 to RAND_MAX. It needs srand to set the starting point for generating random numbers
Insert picture description here
Insert picture description here

Insert picture description here
The starting point for srand to generate random numbers should be before rand.
If the starting point of the random number is unchanged, the comb is the same every time.
Insert picture description here
So here we use the timestamp to set the starting point of a changing random number. After that, the number changes at this starting point. The
timestamp is the time() function, which is replaced by a null pointer internally.
Insert picture description here
The random number n is generated
Insert picture description here
. The range of the random number is reduced and the% method is used.
Insert picture description here
So the game is designed to
Insert picture description here
Insert picture description here
Insert picture description here
run as a result
Insert picture description here

to sum up

Random number generation by rand() requires a random number starting point.
If there is no random number starting point, each run will default to the same starting point (this number will change, but the starting point is the same for different runs), so the random number generated by each run is the same.

Although srand (fixed number) sets the starting point, the numbers generated in one run are the same, so a timestamp is required to set the starting point of the random number, so that it will change in the same run and will not generate the same The
starting point of the random number in different runs is different and it will not be the same as the random number in the previous run.

Guess you like

Origin blog.csdn.net/dodamce/article/details/112858341