1随机数的生成
1.1rand函数
int rand (void);
rand函数会返回⼀个伪随机数,这个随机数的范围是在0~RAND_MAX之间,RAND_MAX的大小是 依赖编译器上实现的,但是⼤部分编译器上是32767。 rand函数的使⽤需要包含⼀个头。其实rand函数⽣成的随机数是伪随机的,伪随机数不是真正 的随机数,是通过某种算法⽣成的随机数。真正的随机数的是⽆法预测下⼀个值是多少的。而rand函 数是对⼀个叫“种⼦”的基准值进⾏运算⽣成的随机数。文件是:stdlib.h
1.2srand
void srand (unsigned int seed);
程序中在调⽤ rand 函数之前先调⽤ srand 函数,通过 srand 函数的参数seed来设置rand函数⽣成随 机数的时候的种⼦,只要种⼦在变化,每次⽣成的随机数序列也就变化起来了。
1.3time
time_t time (time_t* timer);
time 函数会返回当前的⽇历时间,其实返回的是1970年1⽉1⽇0时0分0秒到现在程序运⾏时间之间的 差值,单位是秒。返回的类型是time_t类型的,time_t 类型本质上其实就是32位或者64位的整型类型。
time函数的参数 timer 如果是⾮NULL的指针的话,函数也会将这个返回的差值放在timer指向的内存中带回去。 如果 timer 是NULL,就只返回这个时间的差值。time函数返回的这个时间差也被叫做:时间戳。 time函数的时候需要包含头⽂件:time.h
如果只是让time函数返回时间戳:
time(NULL);//调⽤time函数返回时间戳,这⾥没有接收返回值
1.4设置随机数的范围
⽣成0~99之间的随机数:
rand() %100;//余数的范围是0~99
⽣成1~100之间的随机数
rand()%100+1;//%100的余数是0~99,0~99的数字+1,范围是1~100
⽣成100~200的随机数:
100 + rand()%(200-100+1)
//余数的范围是0~100,加100后就是100~200
生成a到b的随机数:
a + rand()%(b-a+1)
2猜数字游戏
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void game()
{
int r = rand()%100+1;
int guess= 0;
while(1)
{
printf("请猜数字>:");
scanf("%d", &guess);
if(guess < r)
{
printf("猜⼩了\n");
}
else if(guess > r)
{
printf("猜⼤了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
}
}
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;
}
如果加上次数限制:
#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);
count--;
printf("请猜数字>:");
scanf("%d", &guess);
if (guess < r)
{
printf("猜⼩了\n");
}
else if (guess > r)
{
printf("猜⼤了\n");
}
else
{
printf("恭喜你,猜对了\n");
break;
}
}
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;
}