一:猜数字游戏
*rand
int rand (void);
c语⾔提供了⼀个函数叫 rand,这函数是可以⽣成随机数的,函数原型如图所示
*rand函数的使⽤需要包含⼀个头⽂件是:stdlib.h
但是rand函数⽣成的随机数是伪随机的,伪随机数不是真正 的随机数,是通过某种算法⽣成的随机数。真正的随机数的是⽆法预测下⼀个值是多少的。⽽rand函 数是对⼀个叫“种⼦”的基准值进⾏运算⽣成的随机数。 rand函数⽣成随机数的默认种⼦是1。
*srand
void srand (unsigned int seed);
C语⾔中⼜提供了⼀个函数叫 srand,⽤来初始化随机数的⽣成器的,srand的原型如图:
程序中在调⽤ rand 函数之前先调⽤ srand 函数,通过 srand 函数的参数seed来设置rand函数⽣成随机数的时候的种⼦,只要种⼦在变化,每次⽣成的随机数序列也就变化起来了。 那也就是说给srand的种⼦是如果是随机的,rand就能⽣成随机数。
*time
time_t time (time_t* timer);
在程序中我们⼀般是使⽤程序运⾏的时间作为种⼦的,因为时间时刻在发⽣变化的。 在C语⾔中有⼀个函数叫 time ,就可以获得这个时间。
*本质上time_t是longlong或int类型
*time函数的时候需要包含头⽂件:time.h
time函数的参数 timer 如果是⾮NULL的指针的话,函数也会将这个返回的差值放在timer指向的内存 中带回去。 如果 timer 是NULL,就只返回这个时间的差值。time函数返回的这个时间差也被叫做:时间戳。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
//使⽤time函数的返回值设置种⼦
//因为srand的参数是unsigned int类型,我们将time函数的返回值强制类型转换
srand((unsigned int)time(NULL));
printf("%d\n", rand()%100+1);//生成0-100的随机数
printf("%d\n", rand()%100+1);
printf("%d\n", rand()%100+1);
printf("%d\n", rand()%100+1);
printf("%d\n", rand()%100+1);
return 0;
}
*生成a到b的随机数
a + rand()%(b-a+1)
*猜数字游戏实现
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void game()
{
int r = rand() % 100 + 1;
int guess = 0;
int count = 5;
while (count)
{
printf("\n你还有%d次机会\n", count);
printf("请猜数字>:");
scanf("%d", &guess);
if (guess < r)
{
printf("猜小了\n");
}
else if (guess > r)
{
printf("猜大了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
count--;
}
if (count == 0)
{
printf("你失败了,正确值是:%d\n", r);
}
}
void menu()
{
printf("***********************\n");
printf("****** 1. play ******\n");
printf("****** 0. exit ******\n");
printf("***********************\n");
}
int main()
{
int input = 0;
srand((unsigned int)time(NULL));
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;
}