C语言写游戏-猜数字游戏,时间戳的应用

猜数字游戏

效果如下:

1.电脑会生成一个随机数2.猜数字
          rand()需要调用#include <stdlib.h>头文件
          使用time()函数需要引用头文件#include <time.h>

用时间戳生成随机数——猜数字游戏

用rand()函数生成随机数:
在调用rand()函数生成随机数之前,需要使用srand()函数来为rand()函数设置随机数的起点,用时间戳作为srand函数的参数来设置随机数的生成起始点 

时间戳:
当前计算机的时间减去计算机的起始时间(1970年1月1日0时0分0秒)=(xxxxx)秒,即为时间戳;
time()函数返回时间戳(time()函数的参数类型为time_t*的指针)
time()函数返回的值是time_t类型,time_t的本质是long长整型


srand()函数的参数需为unsigned int即无符号整型, 而time_t的本质是long长整型,就可以用(unsigned int)强制转换为无符号整型
注:随机数起点不要频繁设置,频繁设置随机效果不好,所以要放在循环外面  

#include <stdio.h>
#include <string.h>
#include <Windows.h>
#include <stdlib.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>

void menu()
{
	printf("****************************\n");
	printf("***** 1.play  0.exit   *****\n");
	printf("****************************\n");
}
void game()
{
	//游戏本体
	
	int ret = 0;
	int guess = 0;//接收猜的数字
	//1.生成一个随机数,
	ret = rand() % 100 + 1;//把随机数限定到1-100之间
	                       //rand()生成随机数函数,需要sranf()函数设置随机起点
	//2.猜数字
	while (1)
	{
		printf("请猜数字:");
		scanf("%d", &guess);
		if (guess > ret)
		{
			printf("猜大了\n");
		}
		else if (guess < ret)
		{
			printf("猜小了\n");
		}
		else
		{
			printf("恭喜你,猜对了!\n");
			break;
		}
	}

}
							        

int main()   //时间戳:当前计算机的时间减去计算机的起始时间(1970年1月1日0时0分0秒)=(xxxxx)秒即为时间戳

{
	int input = 0;
//     强制转换为无符号整型																																	
//	          ↓                                                                                                                                                          
	srand((unsigned int)time(NULL));//在调用rand()函数生成随机数之前,需要使用srand()函数来为rand()函数设置随机数的起点,用时间戳作为srand函数的参数来设置随机数的生成起始点;注:随机数起点不要频繁设置,频繁设置随机效果不好,所以要放在循环外面
//	   ↑                 ↑
//     ↑                time()函数返回时间戳 ————> time(time_t*timer)函数 ; time()函数返回的值是time_t类型。
//  srand()函数的参数需为unsigned int即无符号整型                  ↑                                    ↑
	do  //                                           time()函数的参数类型为time_t*的指针                time_t的本质是long长整型
	{
		menu();
		printf("请选择:");
		scanf("%d", &input);
		switch (input)
		{
		case 1:
				game();//进入到游戏
				break;
		case 0:
			printf("退出游戏\n");
			break;
		default:
			printf("选择错误\n");
			break;
		}
	} 
	while (input);
	
	return 0;
}

猜数字的过程相当于折半查找,比如数字是5,假如猜10提示猜大了,范围缩小到10以内,假如猜3提示猜小了,范围缩小到4-9,依此类推直到猜到

可运行程序链接如下,可以玩玩

链接:https://pan.baidu.com/s/1qoe9LRmPW_k-pQGozfTHHA 
提取码:dmfx

猜你喜欢

转载自blog.csdn.net/qq_44928278/article/details/119831812
今日推荐