相信大家都遇到过需要生成随机数字的情形,一般情况一下我们都会用rand函数来实现,但是rand函数生成的是伪随机数字, 也即是你只要知道了第一次生成的随机数,后面的随时数字是有规律可循的,为了解决这个问题我们使rand种子函数srand()的参数为time() 函数
srand( (unsigned)time( NULL ) );time()函数的参数之所以指向NULL是因为time函数规定time()函数有这个规定 如果你传进去的是一个null指针,那么系统返回当前时间,(否者不是NULL)那么系统认为你要修改当前时间,就把你传进去的指针对应的time_t变量的值设置为当前时间,而我们的目的就是返回当前时间,这样你的srand()的返回值就不一样了,实现的随机数不再那么的有规律了。number=rand()%100;这句代码的意思生成1到100之间的随机数,利用了数a%100的余数只能在1到100之间。
说了这么多,下面给大家举个数字竞猜的游戏吧,具体代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int number;
int usernumber;
int main()
{
int n=0;
srand( (unsigned)time( NULL ) );
number=rand()%100;
for(n=0;n<10;n++)
{
printf("Please enter the number:\n");
scanf("%d",&usernumber);
if(usernumber>number)
{
printf("The number you entered is bigger than the number created!\n");
}
if(usernumber<number)
{
printf("The price you entered is smaller than the number created!\n");
}
if(usernumber==number)
{
printf("This is the number created!");
}
}
if(n==10)
printf("GAME OVER!!!\n");
return 0;
}