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

c/c++随机数,该如何解决

2012-02-04 
c/c++随机数问个问题for(i0i 6i++){srand((unsigned)time(NULL)+i)tmpnumrand()%10for(jij 5j+

c/c++随机数
问个问题   for   (i=0;i <6;i++)
      {
            srand(   (unsigned)time(   NULL   )+i);
            tmpnum   =   rand()%10;  
              for(j=i;j <5;j++)
                  tmpnum   =   tmpnum*10;
            num   =   num   +   tmpnum;    
        }
如果2次调用的时间很短.就会产生一样的的结果了       就是最后得到的num值都是一样额
怎么避免

[解决办法]
srand( (unsigned)time( NULL ))放循环外面就可以了, 没有必要每次都改变种子吧?

[解决办法]
#include "iostream.h "
#include "time.h "
#include "stdlib.h "

int main(int argc, char* argv[])
{
time_t t;
srand((unsigned)time(&t));
cout < < "Ten random numbers from 0 -- 99 " < <endl;;
for(int i = 0; i < 10; i++)
{
cout < <rand()%100 < < " ";
}
cout < <endl;
return 0;
}
[解决办法]
srand( (unsigned)time( NULL )+i); //种种子的过程放到外面
for (i=0;i <6;i++)
{
tmpnum = rand()%10;
for(j=i;j <5;j++)
tmpnum = tmpnum*10;
num = num + tmpnum;
}
[解决办法]
#include "iostream.h "
#include "time.h "
#include "stdlib.h "

int main() //主函数没必要加参数吧?
{
time_t t;
srand((unsigned)time(&t));
cout < < "Ten random numbers from 0 -- 99 " < <endl;;
for(int i = 0; i < 10; i++)
{
cout < <rand()%100 < < " ";
}
cout < <endl;
return 0;
}

热点排行