MSDN上的例子:
- /*
- Remarks
- The srand function sets the starting point for generating a series of pseudorandom integers.
- To reinitialize the generator, use 1 as the seed argument. Any other value for seed sets the
- generator to a random starting point. rand retrieves the pseudorandom numbers that are generated.
- Calling rand before any call to srand generates the same sequence as calling srand with seed passed as 1.
- */
- #include <stdlib.h>
- #include <stdio.h>
- #include <time.h>
- void main( void )
- {
- int i;
- /* Seed the random-number generator with current time so that
- * the numbers will be different every time we run.
- */
- srand( (unsigned)time( NULL ) );
- /* Display 10 numbers. */
- for( i = 0; i < 10;i++ )
- printf( " %6d/n", rand() );
- }
这是产生随机数的经典用法.在<Linux 0.01内核分析与操作系统设计>这本书中看到这两个函数的实现方法.
- //1.rand()函数
- unsigned _seed;//注意此处为全局变量
- unsigned rand(void)/*stdlib.h*/
- {
- if(_seed==0)
- _seed=1;
- if( (((_seed<<3)^_seed ) & 0x80000000L )!=0)
- _seed=(_seed<<1) | 1;
- else
- _seed<<=1;
- return _seed-1;
- }
- //2.srand()函数
- extern unsigned _seed;/*in rand.c*/
- void srand( unsigned new_seed) /*stdlib.h*/
- {
- _seed=new_seed;
- }
注意这两个函数与C定义的函数运行结果不相同.
但至少让我们对它们的关系,用法更为了解.