C语言产生随机数,个人理解

关于C语言产生随机数的文章网上很多

其实只需要下边三个函数即可

srand();

time( );         

rand();

需要添加头文件

#include
#include


但是我自己尝试了一下,每次产生的数都一样

我的做法如下


#include
#include
#include           //使用当前时钟做种子
unsigned char RandSeed();
void main( void )
{
  int i;
 srand( (unsigned)time( NULL ) );          //初始化随机数
     for( i = 0; i < 10;i++ )
{
          printf( " %d\n",  RandSeed() );
}
}


unsigned char  RandSeed()
{      
   int j;
   srand( (unsigned)time( NULL ) );          //初始化随机数
   j=rand()%4;
   return j;
}



几次之后成功了,原来 srand( (unsigned)time( NULL ) ); 只需要执行一次,

如果每次都执行srand( (unsigned)time( NULL ) );  的话,产生的数值都是一样的


成功的代码如下


#include
#include
#include           //使用当前时钟做种子
unsigned char RandSeed();
unsigned char kkkk,ggg;
void main( void )
{
  int i;
 srand( (unsigned)time( NULL ) );          //初始化随机数
     for( i = 0; i < 10;i++ )
{
          printf( " %d\n",  RandSeed() );
}
}


unsigned char  RandSeed()
{      
   int j;
   j=rand()%4;
   return j;
}


你可能感兴趣的:(C语言)