写一个猜数字游戏
rand
c语言提供了一个函数叫rand,这个函数可以生成随机数
int rand (void);
rand函数会返回一个伪随机数,范围0~RAND_MAX之间,这个最大值的大小是依赖编译器实现的
但大部分编译器是32767(7FFFF)
头文件是:stdlib.h
int r = rand();
rand函数是对"种子"这个基准值生成随机数的 默认的种子是1
srand
是初始化随机数的生成器
void srand (unsigned int seed);
程序在调用rand之前先调用srand函数
通过srand函数的参数seed来设置rand的函数生成随机数的种子
time
一般使用程序运行的时间作为种子
函数time就可以获得这个时间
time函数返回的是一个时间戳 单位是秒
time函数原型:time_t time (time_t* timer);
返回类型是time_t类型(32或64位的整型类型
头文件time.h
time函数的参数timer如果是非NULL的指针的话,函数也会将这个返回的插值放在timer指向的内存中带回去
如果timer是NULL,就只返回这个时间的差值
void menu()
{
printf("************************\n");
printf("******** 1.play *******\n");
printf("******** 0.exit *******\n");
printf("************************\n");
}
猜数字游戏的实现
void game()
{
1.生成随机数(1~100)
int ret = rand()%100 + 1;
//余数的取值范围1~100
2.猜数字
int guess = 0;
while (1)
{
printf("请猜数字:>");
scanf("%d", &guess);
if (guess < ret)
{
printf("猜小了\n");
}
else if (guess > ret)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
}
}
int main()
{
srand((unsigned)time(NULL));
int input = 0;
do
{
menu();
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case(1):
game();
break;
case(0):
printf("退出游戏\n");
break;
default:
printf("选择错误\n");
break;
}
} while (input);
return 0;
}
还可以加上次数的限制
void menu()
{
printf("************************\n");
printf("******** 1.play *******\n");
printf("******** 0.exit *******\n");
printf("************************\n");
}
void game()
{
int ret = rand() % 100 + 1;
int guess = 0;
int count = 5;
while (count)
{
printf("\n你还有%d次机会\n", count);
printf("请猜数字:>");
scanf("%d", &guess);
if (guess < ret)
{
printf("猜小了\n");
}
else if (guess > ret)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
count--;
}
if (count == 0)
{
printf("你失败了,正确值是%d\n", ret);
}
}
int main()
{
srand((unsigned)time(NULL));
int input = 0;
do
{
menu();
printf("请选择:>");
scanf("%d", &input);
switch (input)
{
case(1):
game();
break;
case(0):
printf("退出游戏\n");
break;
default:
printf("选择错误\n");
break;
}
} while (input);
return 0;
}