生成随机数 random value generation

下面给出了生成随机数的函数应用,但光知道怎么用,应用中还是会出问题。知道为什么可以用,知道它是怎么来得更重要。就像数学公式,理解它的原理比用它更重要。The C programming language 会讲得比较彻底一些,告诉你它是怎么来的。

the standard libary includes a portable implementation of a pseudo-random number generator and a function for initializing the seed;the former illustrate a cast:

 1 unsigned long int next = 1;
 2 //rand: return pseudo-random integer on 0..32767
 3 int rand(void)
 4 {
 5     next = next * 1103515245 + 12345;
 6     return(unsigned int)(next/65536) % 32768;
 7 }
 8 //srand: set seed for rand()
 9 void srand(unsigned int seed)
10 {
11     next = seed;
12 }

_____________________

_____random value generation

<stdlib>

rand()//!<generates 0 - 0xFFFF random value.

each time the value generated is different,but they appear in the same oder.

void srand( unsigned seed);  //!<initialize the rand() generator.

long time(long *tloc);    //!return current time in second,if long *tloc is not NULL, returned value is stored in it. 

uint vGenerateRandomValue(void)
{
    unsigned int uiResult;
    srand( (unsigned int)time(0) );   //generate the seeds through time for random value each excution
    uiResult = rand()%max + 1;    //1 - max   are we wanted  
    return uiResult;
}

 srand( time(NULL) );

elementArray[i] = 50-rand() % 100;   //-50 --- 49

原文地址:https://www.cnblogs.com/aprilapril/p/2861808.html