想要完成猜数字游戏,我们得先了解以下知识
一、rand函数
int rand (void);
- rand函数会返回一个伪随机数,这个数的范围是0~RAND-MAX之间,这个RAND-MAX的大小是依赖编译器实现的,但大部分编译器上是32762.
使用rand函数要用一个头文件 stdlib.h
二、srand函数
- c语言中提供了一个函数叫srand,用来初始化随机生成器。
void srand (unsigned int seed);
- 在程序调用rand函数之前先调用srand函数,通过srand函数来设置rand函数生成随机数的时候的种子, 只要种子在变换 每次生成的随机数序列也就变换起来了。
三、time函数
- 在c语言中有一个函数叫time, time函数原型为:
time_t time (time _t * timer);
-time函数会返回当前日历时间,其实返回的是1970年1月1日0时0分0秒到现在程序运行时间之间的差值,单位时秒,返回的类型时time_t类型。 本质上时32位或者64位的整型类型。
- time函数的参数时timer。
- 如果timer是非NULL的指针的话,函数也会将这个返回的差值放在timer指向的内存中带回去。
- 如果timer是NULL,就会返回这个时间从差值。 time函数返回的这个时间差也被叫做时间戳。
- 使用time函数的时候要包含头文件time.h
四、设置随机数的范围
- 生成0~99之间的随机数
rand ()%100;
- 生成1~100之间的随机数
rand ()%100+1;
- 生成100~200之间的随机数
100+rand()%(200-100+1);
- 生成a~b的随机数,方法如下
a + rand ()%(b-a+1);
五、ok掌握以上知识和前面的知识相结合就能写出猜数字游戏啦!!!
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void caidan()
{
printf("****************************\n");
printf("********* 1.play *********\n");
printf("********* 0.exit *********\n");
printf("****************************\n");
}
void game()
{
//1.生成一个随机数
int r =rand()% (100 + 1);
//2.猜数字
int guess = 0;
int cishu = 5;//最多猜5次
while ( cishu )
{
printf("你还有%d次机会", cishu);
printf("请猜数字:\n");
scanf("%d", &guess);
if (guess > r)
printf("猜大了\n");
else if (guess < r)
printf("猜小了\n");
else
{
printf("恭喜你猜对了,随机数是%d\n",r);
break;
}
cishu--;
}
if (cishu == 0)
printf("你失败了,正确的数字是%d\n",r );
}
int main()
{
int input = 0;
srand((unsigned)time(NULL));
do
{
//打印菜单
caidan();
printf("请选择:");
scanf("%d", &input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("游戏结束\n");
break;
default:
printf("选择错误,请重新选择\n");
break;
}
} while ( input );
return 0;
}