6. Generate random numbers and guess number games (rand function, srand function, time function)

1. Generate random numbers

1.1 rand function

The function prototype is as follows:

int rand(void);

Required header file: stdlib.h

Function: Randomly returns one after callingpseudorandom number, the random number range is between 0~RAND_MAX, which is 32767 on most compilers (the rand function is opened with ctrl+left mouse button and is defined as: #define RAND_MAX 0x7fff )

Pseudo-random number: The reason why it is a pseudo-random number is that the rand() function generates random numbers based on a reference value called "seed" .
About the seed: The default seed base value in the rand function is 1
, so you need to use the srand() function (mentioned later) to initialize the seed base value.

Example:

#include <stdio.h>
#include <stdlib.h>
int main() {
    
    
	printf("%d\n", rand());
	printf("%d\n", rand());
	printf("%d\n", rand());
	return 0;
}

I called the rand function three times here, and the results are as follows:
41
18467
6334
Then I re-executed the program many times, and the random number did not change. It has always been these numbers. This
is what is called here.pseudorandom number, so the real change of the random number is achieved by calling the srand() function to change the **seed**

1.2 srand function

The function prototype is as follows:

void srand(unsigned int seed);
The parameter in srand() is a non-negative integer seed
. This non-negative integer seed is the so-called seed, which determines the random number returned by the rand() function.

Function: Initialize the random number generator.
The essence of the function: that is, the seed in srand (unsigned int seed) must be random, and only the rand() function can generate a truly random number.

Question: Does this sound contradictory?
rand() requires seed to be a random value when generating random numbers.
When srand(seed) defines seed, it also needs a random value. The random number of rand has not been generated yet, so where does the random number come from?

Solution: As long as the seed value changes all the time, you can make rand call the function different every time,
so you need to use the time() function next.

1.3 time function

Reason: Use the time when the program is running as the initial value of the seed, because the time is changing all the time

The function prototype is as follows:

time_t time(time_t * timer);

Required header file: time.h

Function: When the time() function parameter is NULL , return the currentTimestamp; If timer is a non-NULL pointer, the function will put the timestamp in the memory pointed to by timer and bring it back.

Timestamp: That is, the time difference between 0:00:00 on January 1, 1970 and the current running of the program. The unit is seconds. The
return type is time_t, which is essentially long (32-bit long integer) or long long (64-bit long integer)

Example: Generate random numbers

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    
    
	//time()函数 参数为NULL时,返回当前时间戳,作为种子
	//因为srand函数的参数时unsigned int类型,所以将time函数的返回值类型强制转换
	unsigned int seed = (unsigned int)time(NULL);
	//初始化seed
	srand(seed);
	//调用rand() 并打印随机数
	printf("调用随机值(整型):%d\n", rand());
	return 0;
} 

Result: As time changes, the random numbers generated are different each time.
Note: The srand function only needs to be called once in a program, and does not need to be called repeatedly!

1.4 Set the range of random numbers

For example: we want to generate random numbers between 0 and 99, the method is as follows

 rand() % 100;//余数的范围为0~99

Principle:
The range of the rand() return value is 0-32767. In terms of digits, the range is [10,000s ~ units].
% 100 = the last two digits of this number. Example: 32699 % 100 = 99 32600 % 100 = 0
Number in the thousands digit level % 100 = Example of the last two digits of this number: 3299 % 100 = 99 3200 % 100 = 0
Number in the hundreds digit level % 100 = Example of the last two digits of this number: 199 % 100 = 99 100 % 100 = 0
, tens-level numbers % 100 = the number itself Example: 99 % 100 = 99 0 % 100 = 0

Based on the above conclusion, to generate a random number between 1 and 100, the method is as follows

 rand() % 100 + 1;//余数的范围为1~100



To generate a random number between 100 and 200, the method is as follows

 100 + rand() % (200 - 100 + 1);//余数的范围为0~100,加100后就是100~200

Summary: If you want to generate random numbers between ab, the method is as follows

a + rand() % (b - a + 1);

2. Guess the number game

#define  _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void game() {
    
    
	int num = rand() % 100 + 1;//生成随机数(范围1-100)
	int guess = 0;//初始化 输入猜的数字
	int count = 5;//设置挑战次数

	while (count)
	{
    
    
		printf("你还有%d次机会,请输入你猜的数字:",count);
		scanf("%d", &guess);
		
		if (guess < num)
		{
    
    
			printf("猜小了\n");
			
		}
		else if (guess > num)
		{
    
    
			printf("猜大了\n");
		}
		else
		{
    
    
			printf("猜对了!\n");
			break;
		}
		count--;
	}
	if (count == 0)
	{
    
    
		printf("你失败了,正确答案是:%d\n",num);
	}
}

void menu() {
    
    

	printf("********************\n");
	printf("***  1.开始游戏  ***\n");
	printf("***  2.退出游戏  ***\n");
	printf("********************\n");
}

int main() {
    
    
	int input = 0;
	srand((unsigned int)time(NULL));//初始化种子,让rand()可以调用随机数
	do
	{
    
    
		menu();
		printf("请选择:");
		scanf("%d", &input);
		switch (input)
		{
    
    
		case 1:
			game();
			break;
		case 2:
			printf("游戏结束\n");

			//这里的break跳出的是switch结构,不用goto弹出游戏结束后还会继续循环菜单
			goto out;
			break;
		default:
			printf("选择错误,请重新选择\n");
			break;
		}
	} while (input);

	out:
	printf("成功退出游戏");
	return 0;
}

running result
Insert image description here

Guess you like

Origin blog.csdn.net/qq_45657848/article/details/132005256