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

哪位大哥帮小弟我看一上随机数的有关问题

2012-08-15 
哪位大哥帮我看一下随机数的问题[b][/b]#include iostream#include ctime#include stdlib.husing na

哪位大哥帮我看一下随机数的问题
[b][/b]#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
void main(){
int t,i;
for(i=1;i<=10;i++){
 srand(time(0));
 t = 1+(int)(10.0*rand()/(RAND_MAX+1.0));
 cout<<i<<':'<<t<<endl;
}
}
我的程序每次运行产生同一个值,不知怎么回事,我想的是在1-10之间随机选5个不重复的数,每次选随机数不一样,且每次不重复,哪位大侠帮忙啊

[解决办法]
srand(time(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 );}
[解决办法]
srand();的作用是初始化随机数发生器。所以只需要初始化一次就可以了。将srand(time(0))放到循环的外面就可以了
[解决办法]
你for循环里太快就结束了,其实造成结果每次srand时候,
种子值一样,产生的第一个随机数当然一样
要想使用时间来srand
C/C++ code
#include <iostream>#include <ctime>#include <stdlib.h>#include <windows.h>using namespace std;void main(){    int t,i;    for(i=1;i<=5;i++)    {        time_t m_time ;        time(&m_time);        srand(m_time);        //cout<<m_time<<endl;        /t = 1+(int)(10.0*rand()/(RAND_MAX+1.0));        //t = rand() ;        cout<<i<<':'<<t<<endl;        Sleep(1000);    }}
[解决办法]
C/C++ code
int RandomInt(int iMin, int iMax){    if(   iMin   >=   iMax   )   return   iMin;       srand(GetTickCount());    return   iMin   +   rand() %   (   iMax   -   iMin   +   1   );  } 

热点排行