srand和 rand函数.

MSDN上的例子:
  1. /*
  2. Remarks
  3. The srand function sets the starting point for generating a series of pseudorandom integers. 
  4. To reinitialize the generator, use 1 as the seed argument. Any other value for seed sets the 
  5. generator to a random starting point. rand retrieves the pseudorandom numbers that are generated.
  6.  Calling rand before any call to srand generates the same sequence as calling srand with seed passed as 1.
  7. */
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <time.h>
  11. void main( void )
  12. {
  13.    int i;
  14.    /* Seed the random-number generator with current time so that
  15.     * the numbers will be different every time we run.
  16.     */
  17.    srand( (unsigned)time( NULL ) );
  18.    /* Display 10 numbers. */
  19.    for( i = 0;   i < 10;i++ )
  20.       printf( "  %6d/n", rand() );
  21. }

这是产生随机数的经典用法.在<Linux 0.01内核分析与操作系统设计>这本书中看到这两个函数的实现方法.

  1. //1.rand()函数
  2. unsigned _seed;//注意此处为全局变量
  3. unsigned rand(void)/*stdlib.h*/
  4. {
  5.      if(_seed==0)
  6.            _seed=1;
  7.      if( (((_seed<<3)^_seed ) & 0x80000000L )!=0)
  8.            _seed=(_seed<<1) | 1;
  9.      else
  10.            _seed<<=1;
  11.      return _seed-1;
  12. }
  13. //2.srand()函数
  14. extern unsigned _seed;/*in rand.c*/
  15. void  srand( unsigned  new_seed) /*stdlib.h*/
  16. {
  17.    _seed=new_seed;
  18. }

注意这两个函数与C定义的函数运行结果不相同.

但至少让我们对它们的关系,用法更为了解.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值