+ -
当前位置:首页 → 问答吧 → 循环里srand(time(0))和rand()为什么在执行时显示的是几个同样的数,而在单步调试时每次显示不同数字呢;

循环里srand(time(0))和rand()为什么在执行时显示的是几个同样的数,而在单步调试时每次显示不同数字呢;

时间:2011-12-21

来源:互联网

#include <iostream>
#include <cstdlib>
#include <ctime>
const int MAX=10;

int main()
{
int times,i=0;
std::cin>>times;
while(i!=5)
{
srand(time(0));
int hello=rand();
std::cout<<hello%MAX<<" ";
i++;
}
return 0;
}
上面的代码为什么在直接执行时每次循环都产生几个相同的数字,而如果下断点,单步的话,每次又显示不同的数字呢

作者: zoelva   发布时间: 2011-12-21

不要每次rand()前都重新srand(),因为你这样的话每次都重置第一个随机数(即种子),而time()返回的数值不会相差很大,所以第一个数由于time()返回值过于接近而不随机

最好从第二次rand()开始取数,而srand()只用一次

作者: yisikaipu   发布时间: 2011-12-21

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 );
}

作者: zhao4zhong1   发布时间: 2011-12-21