当前位置:网站首页>C language explanation series - comprehensive exercises, guessing numbers games
C language explanation series - comprehensive exercises, guessing numbers games
2022-07-26 06:00:00 【Sad pig, little pig】
Topic requirements
Today I will share with you a simple number guessing game , As a comprehensive exercise we learned before , Our need is :
1. You can generate one automatically 1-100 Random number between
2. Players guess numbers , If you're right , Congratulations to the game player. , Game over , If you guess wrong, continue to guess until you get it right
3. The game can be played repeatedly , Unless the player himself quits the game
Thought analysis
First , Friends who have played games know that , Generally, games have a main interface , So let's design a main interface for our game
void menu()
{
printf("******************\n");
printf("******************\n");
printf("****1. Start the game ****\n");
printf("****0. End the game ****\n");
printf("******************\n");
printf("******************\n");
printf("******************\n");
}
Because I said in the need , Our game can be played repeatedly , So our main interface should appear again after the game , So we can use circular statements to realize , According to the needs of the topic, you can know , We need to play a game first to decide whether to continue playing , So use do while sentence .
void menu()
{
printf("******************\n");
printf("******************\n");
printf("****1. Start the game ****\n");
printf("****0. End the game ****\n");
printf("******************\n");
printf("******************\n");
printf("******************\n");
}
int main()
{
do
{
menu();
}while(1);
return 0;
}
As shown in the figure above, we will write menu() Function is called in the main function , Cycle to generate the main interface , But the real game is not like this , We need to let players choose whether to play the game , So we still need to judge .
void menu()
{
printf("******************\n");
printf("******************\n");
printf("****1. Start the game ****\n");
printf("****0. End the game ****\n");
printf("******************\n");
printf("******************\n");
printf("******************\n");
}
int main()
{
int input = 0;
do
{
menu();
printf(" Please choose whether to start the game :\n");
scanf("%d", &input);
switch (input)
{
case 1:
{
printf(" Game begins \n");
break;
}
case 0:
{
printf(" Game over \n");
break;
}
default :
{
printf(" Your choice is wrong , Please reselect :\n");
break;
}
}
}while(input);
return 0;
}
Let me explain the above code , First we enter the cycle , Prompt the player to choose whether to start the game , After entering switch Select statement , Judge the branch entrance according to the player's choice . The judgment condition of the cycle is the choice entered by the player , Let's see if the logic is correct , When the player enters 0 When the game is over , Out of the loop , When players enter other , Start the game or choose again , Continue to cycle , So the logic is right . Of course, our game can't just start with four words , So we need to improve the main part of the game , On the first code :
void game()
{
int num = rand()%100+1;//rand() Library function , return type int Parameters void Randomly generate one 0—RAND_MAX(32767) Number between , But it's not random , The random numbers generated each time are the same
// Need to use srand() Function to set the random number generator , Calling rand Before , Set a random starting point .
int guess = 0;
while (1)
{
printf(" Please enter the number you guessed :\n");
scanf("%d", &guess);
if (guess > num)
{
printf(" Guess the \n");
}
else if (guess < num)
{
printf(" Guess a little \n");
}
else
{
printf(" Congratulations on your guesses , Game over \n");
break;
}
}
}
Our general idea is , First, a random number should be randomly generated for players to guess , Use rand() function ,( We will explain this library function in detail later ) Because the word guessing game has right or wrong guesses, it needs to guess words many times , Use while Statements for , Players guess characters , Use branch statements to judge , Prompt players to guess big or small , Until the player guesses right and ends the cycle . The complete code is as follows :
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
printf("******************\n");
printf("******************\n");
printf("****1. Start the game ****\n");
printf("****0. End the game ****\n");
printf("******************\n");
printf("******************\n");
printf("******************\n");
}
void game()
{
int num = rand()%100+1;//rand() Library function , return type int Parameters void Randomly generate one 0—RAND_MAX(32767) Number between , But it's not random , The random numbers generated each time are the same
// Need to use srand() Function to set the random number generator , Calling rand Before , Set a random starting point .
int guess = 0;
while (1)
{
printf(" Please enter the number you guessed :\n");
scanf("%d", &guess);
if (guess > num)
{
printf(" Guess the \n");
}
else if (guess < num)
{
printf(" Guess a little \n");
}
else
{
printf(" Congratulations on your guesses , Game over \n");
break;
}
}
}
int main()
{
int input = 0;
// Time - Time stamp - Calculate the difference between the current time and the starting time of the computer and convert it into seconds .
srand((unsigned)time(NULL));//srand The required parameter type is unsigned, and time() The return value type of the function is time_t So you need to cast
do
{
menu();
printf(" Please choose whether to start the game :\n");
scanf("%d", &input);
switch (input)
{
case 1:
{
game();
break;
}
case 0:
{
printf(" Game over \n");
break;
}
default :
{
printf(" Your choice is wrong , Please reselect :\n");
break;
}
}
}while(input);
return 0;
}
rand() Generation of random numbers of library functions
First of all we have MSDN Search for rand()· This library function
We can see ,rand() The return value type of the library function is int, Parameter is void, Need to call <stdlib.h> The header file , So we can experiment in the code
void game()
{
int num = rand();
printf("%d\n", num);
int guess = 0;
}
We will void game Function is rewritten into the above code , We test the output
It seems that we have achieved the generation of random numbers , But when we execute the program again, we find
It is the same as the random number generated for the first time , This is absolutely impossible , Such a game is not a good game , How can we solve it ? I'm here MSDN In search of answers , stay MSDN It reminds us ,rand() Function generates a 0——RAND_MAX Number of numbers , Before that, we need to call srand() Library function to generate a random number generator , Set the starting point for generating random numbers . There are many friends to ask ,RAND_MAX What is the value of alpha ? We are transitioning from code to definition discovery , It's a 16 Binary number , The conversion 10 Into the system for 32767.
So we know rand() The library function generates a range of 0——32767 The random number , But it is Pseudorandom . We also need to use it before him srand().
We have learned ,srand() The return value of is null , Parameter type is unsigned int, A reference header file is required <stdlib.h>. To implement random numbers , Then his starting point must also be random , But now we need to set the starting point to get random numbers , The setting of the starting point requires random parameters , This is not a wireless doll , Hey , We also have solutions , We waste our computer time , To help us set the starting point of random numbers , We call it Time stamp .
The concept of timestamps : Now the difference between the computer time and the computer start time is converted into seconds, which is the timestamp .
void game()
{
srand((unsigned)time(NULL));
int num = rand();
printf("%d\n", num);
int guess = 0;
}
We execute the code again , Get random number
We find that the random numbers obtained twice are not the same , In this way, we have completed the code of generating random numbers . Let's explain again srand((unsigned)time(NULL)); This statement , First let's understand time()
We see library functions time() The return value of is time_t Parameter is time_t *timer, call time() The function needs to reference the header file <time.h>. but srand() The parameter type of is unsigned So we need to cast , take time() The return value type of becomes unsigned, We don't need this parameter , So just pass in a null value . This is it. srand((unsigned)time(NULL)); The general idea of .
Trial of the game
After writing this game, we can try it
Our game works perfectly , Is there a sense of achievement !
边栏推荐
- 柠檬班自动化学习毕竟
- Database SQL language practice
- Knowledge precipitation I: what does an architect do? What problems have been solved
- 软件测试面试题全网独家没有之一的资深测试工程师面试题集锦
- Redis persistence AOF
- H. Take the Elevator 贪心
- flex布局
- Establishment of log collection and analysis platform-1-environment preparation
- L. Link with Level Editor I dp
- Etcd database source code analysis - cluster membership changes log
猜你喜欢

Qu Weihai, chairman and CEO of Xinyi interactive, adheres to mutual benefit and win-win results, and Qu Weihai promotes enterprise development
![[MySQL must know and know] time function number function string function condition judgment](/img/b2/aa15bf4cd78a3742704f6bd5ecb9c6.png)
[MySQL must know and know] time function number function string function condition judgment

leetcode-aboutString

金仓数据库 KingbaseES SQL 语言参考手册 (6. 表达式)

Print linked list in reverse order

Application of canoe XML in test modules

Database SQL language practice

Redis发布订阅

Redis persistence RDB

Matlab 向量与矩阵
随机推荐
Youwei low code: Brick life cycle component life cycle
Mysql45 talks about transaction isolation: why can't I see it after you change it?
金仓数据库 KingbaseES SQL 语言参考手册 (11. SQL语句:ABORT 到 ALTER INDEX)
Should we test the Dao layer?
递归处理——子问题
Mba-day29 arithmetic - preliminary understanding of absolute value
Application of canoe XML in test modules
Byte interview question - judge whether a tree is a balanced binary tree
5-year-old Test Engineer - how to choose the next step?
"Recursive processing of subproblems" -- judging whether two trees are the same tree -- and the subtree of another tree
EM and REM
Properties of binary tree~
idea yml 文件代码不提示解决方案
em和rem
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(十))
Excitation method and excitation voltage of hand-held vibrating wire vh501tc acquisition instrument
Day110. Shangyitong: gateway integration, hospital scheduling management: Department list, statistics based on date, scheduling details
Introduction to Chinese text error correction task
实习运维知识积累
招标信息获取