猜数字游戏:
- 电脑随机产生一个数字
- 猜数字
随机生成随机数
我们是拿时间戳去设计随机数的生成起始点。
当前计算机的时间 - 计算机的起始时间(1970.1.1.0:0:0) = (xxx)秒
time_t time(time_t *timer)
time_t本质上是long 长整型,需要强制类型转化
就像这样
srand((unsigned int)time(NULL));
只要在程序中放一次就ok
接下来我们看看代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void menu()
{
printf("*************************\n");
printf("*** 1.play 2.exit ****\n");
printf("*************************\n");
}
void game()
{
int guess = 0;
//1.生成一个随机数
int ret = 0;
//拿时间戳设计随机数的生成起始点
//time_t time(time_t *timer)
//time_t
//当前计算机的时间 - 计算机的起始时间(1970.1.1.0:0:0) = (xxx)秒
//time_t本质上是long 长整型,需要强制类型转化
//srand((unsigned int)time(NULL));在程序中放一次就好了
//生成1-100之间随机数
ret = rand() % 100 + 1;
//2.猜数字
while (1)
{
printf("猜数字>:");
scanf("%d", &guess);
if (guess > ret)
{
printf("猜大了");
}
else if (guess < ret)
{
printf("猜小了");
}
else
{
printf("猜对了!");
break;
}
}
}
int main()
{
int input;
srand((unsigned int)time(NULL));
do
{
menu();
printf("请输入>:");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏!");
break;
default:
printf("选择错误!");
break;
}
system("cls");
} while (input);
return 0;
}