关于一个随机数的问题

dqdx_zch 2009-05-10 01:25:38
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include "time.h"
using namespace std;

const int N = 50;

int RangedRandDemo( int range_min, int range_max )
{
srand( (unsigned)time( NULL ) );
int u = (double)rand() / (RAND_MAX + 1) * (range_max - range_min) + range_min;
return u;
}

int _tmain(int argc, _TCHAR* argv[])
{

vector< vector<double> > r(N);
char *names[] = {"RandOD1.txt", "RandOD2.txt", "RandOD3.txt", "RandOD4.txt", "RandOD5.txt",
"RandOD6.txt", "RandOD7.txt", "RandOD8.txt", "RandOD9.txt", "RandOD10.txt"};

ifstream infile_R;
ofstream outfile;

infile_R.open("bcOD.txt");
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
double num;
infile_R >> num;
r[i].push_back(num);
}
}

infile_R.close();


double temp[N][N] = {0};
for (int ix = 0; ix < 10; ++ix)
{
srand( (unsigned)time( NULL ) );
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
temp[i][j] = r[i][j] + ( RangedRandDemo(1, 100) );
}
}
outfile.open(names[ix]);
for (size_t i = 0; i < N; ++i)
{
for (size_t j = 0; j < N; ++j)
{
outfile << temp[i][j] << " ";
}
outfile << endl;
}
outfile.close();
outfile.clear();
}

return 0;
}


我这个程序是想对r[i][j]矩阵,用伪随机数进行10次扰动,产生10个扰动的矩阵,但是为什么10个矩阵都是一样的呢?
达人教教啊!
...全文
118 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
liliangbao 2009-05-10
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 xiaocha 的回复:]
引用 1 楼 lingyin55 的回复:
srand( (unsigned)time( NULL ) );////放到这里看看
double temp[N][N] = {0};
for (int ix = 0; ix < 10; ++ix)
{


因为代码执行很快,多次srand( (unsigned)time( NULL ) );时,
time(NULL)都一样,使得种子相同,从而产生的随即数相同,造成错误
[/Quote]
晕,真的假的~
你测试了吗?
xiaocha 2009-05-10
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 lingyin55 的回复:]
srand( (unsigned)time( NULL ) );////放到这里看看
double temp[N][N] = {0};
for (int ix = 0; ix < 10; ++ix)
{
[/Quote]

因为代码执行很快,多次srand( (unsigned)time( NULL ) );时,
time(NULL)都一样,使得种子相同,从而产生的随即数相同,造成错误
  • 打赏
  • 举报
回复
srand( (unsigned)time( NULL ) );


只需要初始化一次种子,明白不。
aaaa3105563 2009-05-10
  • 打赏
  • 举报
回复
帮顶··
deerwin1986 2009-05-10
  • 打赏
  • 举报
回复
加种子。。。
koulongfei 2009-05-10
  • 打赏
  • 举报
回复
学习....................
liliangbao 2009-05-10
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 lingyin55 的回复:]
srand( (unsigned)time( NULL ) );////放到这里看看
double temp[N][N] = {0};
for (int ix = 0; ix < 10; ++ix)
{
[/Quote]
Up~
strive0 2009-05-10
  • 打赏
  • 举报
回复
scrand(time(0));
试试,随机种子不一样就行了吧应该。。。
mengde007 2009-05-10
  • 打赏
  • 举报
回复
因为随机种子每次都要产生才能有效果;
lingyin55 2009-05-10
  • 打赏
  • 举报
回复
srand( (unsigned)time( NULL ) );////放到这里看看
double temp[N][N] = {0};
for (int ix = 0; ix < 10; ++ix)
{

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧