每次在C++中生成相同的随机数

Kor*_*gay 4 c++ random

这是我的代码:

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";
Run Code Online (Sandbox Code Playgroud)

当我打电话给exe时

sleeper 4 4 
Run Code Online (Sandbox Code Playgroud)

我总是得到2000毫秒,4次......为什么?

rky*_*ser 12

您必须为随机数生成器播种.在这里看一个例子.

未seeded.c

#include <stdio.h>
#include <stdlib.h>

int main ()
{
  printf ("Random not seeded: %d\n", rand()%10);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

无种子输出

Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
Run Code Online (Sandbox Code Playgroud)

seeded.c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  srand(time(NULL));
  printf ("Random seeded: %d\n", rand()%10);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

种子输出

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
Run Code Online (Sandbox Code Playgroud)

快速seeded.c

如果您希望能够每秒多次调用您的实用程序,则必须使用不同的源来为您播种,否则您仍会得到一些重复的随机数.

这是一个使用纳秒而不是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;
}
Run Code Online (Sandbox Code Playgroud)

快速播种的输出

您可以在此处看到,这些数字的分组与前一个示例不同.

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
Run Code Online (Sandbox Code Playgroud)

均匀分布的随机数

如果您对均匀分布的随机数感兴趣,请在下面看到user3003631的答案.如果你实际上在使用C++,那就是我建议做随机数的方法.关于这方面的更多信息.


VIR*_*OID 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案,C rand库应该像瘟疫一样避免 (2认同)