[c language] ------Simple number guessing game

1. Purpose

 The purpose of writing this number-guessing game in C language is mainly to deepen the understanding of some knowledge points and consolidate these knowledge points.

1.1 Generate random numbers

Random numbers are generated using rand(). There is no need to pass in parameters. The range of the generated random numbers is [0, 32767]. It should be noted that the generated random numbers are pseudo-random numbers and they are generated according to a predefined algorithm. And repeat in the same order every time the program runs. Therefore, before using rand, you need to use srand to obtain a random seed. The parameter is an unsigned int to solve the problem of sequence duplication.

1.2 Timestamp

The timestamp refers to the total number of seconds from 00:00:00 on January 1, 1970, Greenwich Mean Time (08:00:00 on January 1, 1970, Beijing time) to the present. Use the time function to generate a timestamp. The parameter is a pointer, and NULL can be used to represent a null pointer.

1.3rand and srand

When implementing the number guessing game, srand cannot be placed inside the loop. If srand((unsigned int)time(NULL)); is placed inside the loop, due to the loop Iterations are very fast and may be executed multiple times in the same second. In this case, the value returned by time(NULL) may be the same, causing the random number generator to be reinitialized with the same seed value.

2. Code

# include<stdio.h>
# include<stdlib.h>
#include<time.h>

void menu()
{
	printf("############################\n");
	printf("####### 1.play  0.exit #####\n");
	printf("############################\n");

}
void play()
{
	int res = rand() % 100 + 1;
	int sum = 0;
	while (1)
	{
		printf("请输入猜的数字;\n");
		scanf("%d", &sum);

		if (sum < res)
		{
			printf("猜小了\n");
		}
		else if (sum > res)
		{
			printf("猜大了\n");
		}
		else
		{
			printf("猜对了\n");
			break;
		}

	}
}

int main()
{
	RAND_MAX;
	srand((unsigned int)time(NULL));
	int input = 0;
	do
	{
		menu();
		printf("请输入选项\n");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
			play();
			break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("输入错误\n");
			break;
		}
		

	} while (input);
	return 0;
}

Guess you like

Origin blog.csdn.net/2201_75443644/article/details/131131532