rand函数产生随机数

本来想用下面的程序来对数组中的元素进行设置。可是实际情况是如果产生的六个随机数,每两个都是相同的,如果去掉srand,那么每次运行产生都会产生六个不同的随机数,可是每次运行随机数的产生都是相同的,请高手指点。下面是源程序。
#include<iostream>
using namespace std;
#include<conio.h>
#include<stdlib.h>
#include<time.h>
void suijishu(int mapname[][10])
{

int number1,number2,number_rand=4;//生成number_rand-1个炸弹。
while(number_rand--)//
{
srand((int)time(0));//生成随机数生成器种子
number1=rand()%10;//生成0-9的随机数
number2=rand()%10;
if(mapname[number1][number2]==3)
{
continue;//保证随机生成的炸弹位置不在出口。
}
if(mapname[number1][number2]==2)
{
continue;//保证随机生成的炸弹位置不在入口。
}
mapname[number1][number2]=5;
cout<<number1<<endl;
cout<<number2<<endl;
}

}
void main()
{
int map1[10][10]={
1,1,0,0,1,0,0,0,1,2,//0表示道路,1表示墙,
0,0,1,0,0,1,1,0,1,0,
1,0,1,0,0,0,1,0,0,0,
1,0,1,0,1,0,1,0,0,1,
1,0,1,0,1,0,0,0,0,0,
1,0,1,0,0,0,1,1,1,0,
1,0,0,1,0,0,1,0,0,0,
0,0,0,0,0,0,0,1,1,1,
0,1,0,1,1,0,0,0,0,0,
3,1,0,0,0,1,1,1,1,0//2表示入口,3表示出口
};
suijishu(map1);
/* for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
cout<<map1[i][j]<<" ";
}
cout<<endl;
}
*/
}

计算机产生随机数实际上是使用被成为“伪随机数”的算法,只要你给的种子(通过srand传递的)相同,那么产生的随机数序列就是相同的,这就是为什么如果你去掉srand后,每次运行产生的序列都相同(每次运行种子都相同);但如果你将srand放入循环,且传入的种子是时间戳,那么只要这个时间戳相同,种子便相同,rand()产生的随机序列也相同。循环的每次迭代执行时间极短,按照你的陈述,在你机器上基本上是每迭代两次,使用的是同一个时间戳,故这两个值是相同的。
解决方案:将srand移出循环外部。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-17
#include<iostream>

#include<conio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>//////////////////////////////////////////hereherehere
using namespace std;
void suijishu(int mapname[][10])
{

int number1,number2,number_rand=4;//生成number_rand-1个炸弹。
while(number_rand--)//
{
srand((int)time(0));//生成随机数生成器种子
number1=rand()%10;//生成0-9的随机数
number2=rand()%10;
if(mapname[number1][number2]==3)
{
continue;//保证随机生成的炸弹位置不在出口。
}
if(mapname[number1][number2]==2)
{
continue;//保证随机生成的炸弹位置不在入口。
}
mapname[number1][number2]=5;
cout<<number1<<endl;
cout<<number2<<endl;
}

}
void main()
{
srand(time(NULL)); ////////////////////////////////////////////hereherehere
int map1[10][10]={
1,1,0,0,1,0,0,0,1,2,//0表示道路,1表示墙,
0,0,1,0,0,1,1,0,1,0,
1,0,1,0,0,0,1,0,0,0,
1,0,1,0,1,0,1,0,0,1,
1,0,1,0,1,0,0,0,0,0,
1,0,1,0,0,0,1,1,1,0,
1,0,0,1,0,0,1,0,0,0,
0,0,0,0,0,0,0,1,1,1,
0,1,0,1,1,0,0,0,0,0,
3,1,0,0,0,1,1,1,1,0//2表示入口,3表示出口
};
suijishu(map1);
/* for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
cout<<map1[i][j]<<" ";
}
cout<<endl;
}
*/
}本回答被网友采纳
第2个回答  2013-05-18
srand((int)time(0));放到循环外面

这个函数应该在整个程序运行过程中只调用一次.
相似回答