当前位置:网站首页>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 !
边栏推荐
- Docking wechat payment (II) unified order API
- The time complexity of two recursive entries in a recursive function
- [highly available MySQL solution] centos7 configures MySQL master-slave replication
- MBA-day28 数的概念-练习题
- [Oracle SQL] calculate year-on-year and month on month (column to row offset)
- Introduction to three feasible schemes of grammatical generalization
- Mysql45 speak in simple terms index
- 秋招-准备计划
- [cloud native] record of feign custom configuration of microservices
- 二叉树的前中后序遍历——本质(每个节点都是“根”节点)
猜你喜欢

Modifiers should be declared in the correct order

二叉树的前中后序遍历——本质(每个节点都是“根”节点)

"Recursive processing of subproblems" -- judging whether two trees are the same tree -- and the subtree of another tree

Day110. Shangyitong: gateway integration, hospital scheduling management: Department list, statistics based on date, scheduling details

Acquisition of bidding information

Matlab 向量与矩阵

Establishment of log collection and analysis platform-1-environment preparation

vagrant下载速度慢的解决方法

Modifiers should be declared in the correct order 修饰符应按正确的顺序声明

语法泛化三种可行方案介绍
随机推荐
Lemon class automatic learning after all
Interview questions for software testing is a collection of interview questions for senior test engineers, which is exclusive to the whole network
flex布局
1.12 basis of Web Development
[2023 Jerry technology approval test questions in advance] ~ questions and reference answers
[(SV & UVM) knowledge points encountered in written interview] ~ phase mechanism
VS中使用动态库
Matlab 向量与矩阵
Mysql45 speak in simple terms index
Redis事务
Can you make a JS to get the verification code?
Mysql45 talking about logging system: how does an SQL UPDATE statement execute?
Solution to slow download speed of vagrant
[free and easy to use] holiday query interface
二叉树的前中后序遍历——本质(每个节点都是“根”节点)
L. Link with Level Editor I dp
The idea YML file code does not prompt the solution
Is the transaction in mysql45 isolated or not?
对接微信支付(二)统一下单API
NFT in the eyes of blackash: the platform is crying for slaughter, and users send money to the door