首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

rand()函数在某种情况上,生成的随机数是一样的

2012-07-19 
rand()函数在某种情况下,生成的随机数是一样的?如题,看下面代码:C/C++ code#include stdlib.h#include

rand()函数在某种情况下,生成的随机数是一样的?
如题,看下面代码:

C/C++ code
#include <stdlib.h>#include <stdio.h>#include <time.h>int test_time(){    srand(time(NULL));    return rand()%10000;}int main(){    printf("%d\n", test_time());    printf("%d\n", test_time());    printf("%d\n", test_time());    return 0;}

三次输出的是一样的。

但改成下面这样,就正常了:
C/C++ code
#include <stdlib.h>#include <stdio.h>#include <time.h>int test_time(){    return rand()%10000;}int main(){    srand(time(NULL));    printf("%d\n", test_time());    printf("%d\n", test_time());    printf("%d\n", test_time());    return 0;}


[解决办法]
C:\Program Files\Microsoft Visual Studio 10.0\VC\crt\src\rand.c
C/C++ code
/****rand.c - random number generator**       Copyright (c) Microsoft Corporation. All rights reserved.**Purpose:*       defines rand(), srand() - random number generator********************************************************************************/#include <cruntime.h>#include <mtdll.h>#include <stddef.h>#include <stdlib.h>/****void srand(seed) - seed the random number generator**Purpose:*       Seeds the random number generator with the int given.  Adapted from the*       BASIC random number generator.**Entry:*       unsigned seed - seed to seed rand # generator with**Exit:*       None.**Exceptions:********************************************************************************/void __cdecl srand (        unsigned int seed        ){        _getptd()->_holdrand = (unsigned long)seed;}/****int rand() - returns a random number**Purpose:*       returns a pseudo-random number 0 through 32767.**Entry:*       None.**Exit:*       Returns a pseudo-random number 0 through 32767.**Exceptions:********************************************************************************/int __cdecl rand (        void        ){        _ptiddata ptd = _getptd();        return( ((ptd->_holdrand = ptd->_holdrand * 214013L            + 2531011L) >> 16) & 0x7fff );}
[解决办法]
随机数在某些场合(例如游戏程序)是非常有用的,但是用计算机生成完全随机的数却不是那么容易。计算机执行每一条指令的结果都是确定的,没有一条指令产生的是随机数,调用C标准库得到的随机数其实是伪随机(Pseudorandom)数,是用数学公式算出来的确定的数,只不过这些数看起来很随机,并且从统计意义上也很接近均匀分布(Uniform Distribution)的随机数。

C标准库中生成伪随机数的是rand函数,使用这个函数需要包含头文件stdlib.h,它没有参数,返回值是一个介于0和RAND_MAX之间的接近均匀分布的整数。RAND_MAX是该头文件中定义的一个常量,在不同的平台上有不同的取值,但可以肯定它是一个非常大的整数。通常我们用到的随机数是限定在某个范围之中的,例如0~9,而不是0~RAND_MAX,我们可以用%运算符将rand函数的返回值处理一下:

int x = rand() % 10;

[解决办法]
它这个随机其实是一个随机序列,就是说当调用rand的时候值早已经确定好了,通过srand可以重置随机序列。

热点排行
Bad Request.