我想在for循环中生成三个随机数:
for (i=0; i<100; i++)
{
item1 = rand()/(double)RAND_MAX*100;
item2 = rand()/(double)RAND_MAX*200;
item3 = rand()/(double)RAND_MAX*300;
}
所以我的问题是:
如何为每个项目1,2和3获得等间隔的随机数
如item1 = 10,20,30,40,50 item2 = 40,60,80,item3 = 25,35,45等。
答案 0 :(得分:0)
你想要的数字根本不是随机的,这就是序列
您可以执行类似
的操作int sequence =5;
int initial=10;
For (i=0; i<100; i++)
{
item1 = initial;
initial=initial+sequence;
item2 = initial;
initial=initial+sequence;
item3 = initial;
initial=initial+sequence;
}
它将生成10,15,20 ......
答案 1 :(得分:0)
您只想对随机数进行舍入,或者在生成后缩放/投影它们。
这是...乘法。示例:( Live On Coliru )
#include <random>
#include <iostream>
int main()
{
std::mt19937 engine(time(NULL));
std::uniform_int_distribution<int> dist(0,10); // arbitrary range chosen
for (int i=30; i>0; --i)
{
int random = dist(engine);
std::cout << (random*10) << "\t" << (random*20) << "\t" << (random*10 + 15) << "\n";
}
}
输出:
90 180 105
30 60 45
90 180 105
50 100 65
70 140 85
10 20 25
40 80 55
30 60 45
80 160 95
60 120 75
0 0 15
40 80 55
20 40 35
20 40 35
90 180 105
50 100 65
80 160 95
0 0 15
0 0 15
0 0 15
40 80 55
50 100 65
10 20 25
60 120 75
100 200 115
80 160 95
70 140 85
90 180 105
30 60 45
60 120 75
答案 2 :(得分:-1)
也许您正在尝试获取随机等间隔序列的初始随机数,如下所示:
for (i=0; i<100; i++)
{
if(i == 0)
{
item1 = rand()/(double)RAND_MAX*100;
item2 = rand()/(double)RAND_MAX*200;
item3 = rand()/(double)RAND_MAX*300;
increment1 = rand()/(double)RAND_MAX*100;
increment2 = rand()/(double)RAND_MAX*200;
increment3 = rand()/(double)RAND_MAX*300;
}
else
{
item1 += increment1;
item2 += increment2;
item3 += increment3;
}
//do stuff
}