随机函数的生成 竞猜数字游戏

        相信大家都遇到过需要生成随机数字的情形,一般情况一下我们都会用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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值