这是我的代码:
int main(int argc, char** argv) {
int sleeptime = atoi(argv[1]);
int sleepCount = atoi(argv[2]);
int sleepTimeRandom = 1 + (rand() % (int)(sleeptime));
int sleepCountRandom = 1 + (rand() % (int)(sleepCount));
sleepTimeRandom = sleepTimeRandom * 1000;
DWORD id = GetCurrentProcessId();
cout << "\n\nProcess with id " << id << " will sleep for " << sleepTimeRandom << " milliseconds\n";
cout << "\n\nProcess with id " << id << " will sleep " << sleepCountRandom << " times \n";
当我打电话给exe时
sleeper 4 4
我总是得到2000毫秒,4次......为什么?
答案 0 :(得分:12)
您必须为随机数生成器播种。 see here for an example
#include <stdio.h>
#include <stdlib.h>
int main ()
{
printf ("Random not seeded: %d\n", rand()%10);
return 0;
}
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand(time(NULL));
printf ("Random seeded: %d\n", rand()%10);
return 0;
}
Random fast seeded: 7
Random fast seeded: 7
Random fast seeded: 7
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 5
Random fast seeded: 5
Random fast seeded: 5
Random fast seeded: 5
如果您希望能够每秒多次调用您的实用程序,则必须使用不同的来源为您播种,否则您最终会得到一些重复的随机数。
这是一个使用纳秒而不是time()
的示例,它只返回秒。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
/* using nano-seconds instead of seconds */
srand((time_t)ts.tv_nsec);
printf ("Random fast seeded: %d\n", rand()%10);
return 0;
}
您可以在此处看到,这些数字的分组与前一个示例不同。
Random fast seeded: 9
Random fast seeded: 6
Random fast seeded: 5
Random fast seeded: 6
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 9
Random fast seeded: 4
Random fast seeded: 3
Random fast seeded: 2
如果您对均匀分布的随机数感兴趣,请在下面看到 user3003631 的答案。如果你实际上在使用C ++,那就是我建议做随机数的方法。 More information here too on this.
答案 1 :(得分:8)
C ++中还有随机效用 如果你想要一个不同的方法......可能更高的质量 请原谅最低限度的解释
#include <iostream>
#include <algorithm>
#include <random>
int random_test_200()
{
std::random_device rd;
uniform_int_distribution<int> ud(1,9);
mt19937 mt(rd());
std::vector<int> v1;
for (int i = 0; i < 40; ++i)
{
auto x = ud(mt);
v1.push_back(x);
}
}
答案 2 :(得分:2)
您需要使用time()函数为随机数生成器设定种子,以确保RNG以类似随机的方式运行。在开始生成随机数之前添加srand()调用。