srand和rand的用法

srand((unsigned)time(NULL))是初始化随机函数种子:
1、是拿当前系统时间作为种子,由于时间是变化的,种子变化,可以产生不相同的随机数。
计算机中的随机数实际上都不是真正的随机数,如果两次给的种子一样,是会生成同样的随机序列的。 所以,一般都会以当前的时间作为种子来生成随机数,这样更加的随机。 
2、使用时,参数可以是unsigned型的任意数据,比如srand(10); 3、如果不使用srand,用rand()产生的随机数,在多次运行,结果是一样的。
     void test_rand(void)
     {
           unsigned long n;

          srand((unsigned)time(NULL));

          for(int i = 0; i < 100; i++)
          {
                n = rand();
                printf("d\n", n);
           }
}

 
 
int rand (void);
Generate random number
Returns a pseudo-random integral number in the range between 0 and RAND_MAX.This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.

RAND_MAX is a constant defined in <cstdlib>.

A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

1
2
3
v1 = rand() % 100;         // v1 in the range 0 to 99
v2 = rand() % 100 + 1;     // v2 in the range 1 to 100
v3 = rand() % 30 + 1985;   // v3 in the range 1985-2014 
 


Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值