C语言随机数的总结

来源:互联网 发布:单片机应用技术 推荐 编辑:程序博客网 时间:2024/05/02 04:55
//先来看下面一小段代码#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <time.h>void main(){int i=0;while(i++<10){printf("%-8d",rand());Sleep(500);}}

第一次运行结果为:

41      18467   6334    26500   19169   15724   11478   29358   26962   24464

第二次运行时结果还是一样的。

当时我就挺郁闷的,怎么随机数成了定数啦。昨天有同学再一次把它拿 出来讨论,我觉得还是值得回忆和总结一下的。

下面是MSDN上的函数解释:

Generates a pseudorandom number. A more secure version of this function is available, seerand_s.

 
int rand( void );

Return Value

rand returns a pseudorandom number, as described above. There is no error return.

Remarks

The rand function returns a pseudorandom integer in the range 0 toRAND_MAX (32767). Use the srand function to seed the pseudorandom-number generator before callingrand.


      在C语言中,rand()函数可以用来产生随机数,但是这不是真真意义上的随机数,是一个伪随机数,是根据一个数,我们可以称它为种子,为基准以某个递推公式推算出来的一系数,当这系列数很大的时候,就符合正态公布,从而相当于产生了随机数,但这不是真正的随机数,当计算机正常开机后,这个种子的值是定了的,除非你破坏了系统,为了改变这个种子的值,C提供了srand()函数,它的原形是void srand( int a)。

可能大家都知道C语言中的随机函数random,可是random函数并不是ANSI C标准,所以说,random函数不能在gcc,vc等编译器下编译通过。

rand()会返回一随机数值,范围在0至RAND_MAX 间。返回0至RAND_MAX之间的随机数值,RAND_MAX定义在stdlib.h,(其值至少为32767)我运算的结果是一个不定的数,要看你定义的变量类型,int整形的话就是32767。 在调用此函数产生随机数前,必须先利用srand()设好随机数种子,如果未设随机数种子,rand()在调用时会自动设随机数种子为1。

参数seed必须是个整数,通常可以利用geypid()或time(0)的返回值来当做seed。如果每次seed都设相同值,rand()所产生的随机数值每次就会一样。

设置种子用srand函数。下面是该函数在MSDN 上面的解释

Sets a random starting point.

 
void srand(   unsigned int seed );

Parameters

seed

Seed for random-number generation

Remarks

The srand function sets the starting point for generating a series of pseudorandom integers in the current thread. To reinitialize the generator, use 1 as theseed 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 callingsrand with seed passed as 1.



下面是一位网友的总结,挺好的,在此引用一下:

利用srand((unsigned int)(time(NULL))是一种方法,因为每一次运行程序的时间是不同的。

       在C语言里所提供的随机数发生器的用法:现在的C编译器都提供了一个基于ANSI标准的伪随机数发生器函数,用来生成随机数。它们就是rand()和srand()函数。这二个函数的工作过程如下:

1) 首先给srand()提供一个种子,它是一个unsigned int类型,其取值范围从0~65535;

2) 然后调用rand(),它会根据提供给srand()的种子值返回一个随机数(在0到32767之间)

3) 根据需要多次调用rand(),从而不间断地得到新的随机数;

4) 无论什么时候,都可以给srand()提供一个新的种子,从而进一步“随机化”rand()的输出结果。


那么到这里,就可以改改上面的代码,让每次运行时都 是不一样的代码:

#include <stdio.h>#include <stdlib.h>#include <windows.h>#include <time.h>void main(){int i=0;srand( (unsigned)time( NULL ) );          //初始化随机数while(i++<10){printf("%-8d",rand());Sleep(500);}}

如何产生设定范围内的随机数  呢?当然这些问题,也在很多博客上有的,但还是把贴出来,也算是做个完整的了

 由于rand产生的随机数从0到rand_max,而rand_max是一个很大的数,那么如何产生从X~Y的数呢?

    从X到Y,有Y-X+1个数,所以要产生从X到Y的数,只需要这样写:

    k=rand()%(Y-X+1)+X;

    这样,就可以产生你想要的任何范围内的随机数了。