1. srand和rand() ```c

    include

    include

// 1. rand() 的内部实现是用线性同余法做的,它不是真的随机数,因其周期特别长,故在一定的范围里可看成是随机的。 // 2. rand() 返回一随机数值的范围在 0 至 RAND_MAX 间。RAND_MAX 的范围最少是在32767 之间(int) // 3. rand() 产生的是伪随机数字,每次执行时是相同的; 若要不同, 用函数 srand() 初始化它。 // 4. rand() 不是线程安全的。 int main(int argc, char** argv) { srand(static_cast(time(NULL))); int randomValue = rand(); return 0; }

// 要取得 [a,b) 的随机整数 int RandomBetweenLBRB(int a, int b) { srand(static_cast(time(NULL))); return (rand() % (b - a)) + a; }

// 要取得 [a,b] 的随机整数 int RandomBetweenLBRB(int a, int b) { srand(static_cast(time(NULL))); return (rand() % (b - a + 1)) + a; }

// 要取得 (a,b] 的随机整数 int RandomBetweenLURB(int a, int b) { srand(static_cast(time(NULL))); return (rand() % (b-a))+ a + 1 }

  1. 2. rand_r()函数, rand_r线程安全,且种子和随机放在一个函数里,但是种子必须是1个可以被修改的值,每次rand都会修改种子
  2. ```c
  3. unsigned int seed = static_cast<unsigned int>(time(NULL));
  4. int randomValue = rand_r(&seed);
  5. printf("randomValue: %d, seed changed as: %u\n", randomValue, seed);

可以进行封装

  1. class Rng {
  2. public:
  3. Rng() { seed_ = static_cast<unsigned int>(time(NULL)); }
  4. Rng(unsigned int seed) : seed_(seed) {}
  5. void SetSeed(unsigned int newseed) { seed_ = newseed; }
  6. int Rand() { return rand_r(&seed_); }
  7. private:
  8. unsigned int seed_;
  9. };
  1. c++11 ```cpp

    include

template int randomInt() { static std::default_random_engine engine(std::random_device{}()); static std::uniform_int_distribution distribution(begin, end); return distribution(engine); }

int main(int argc, char** argv) { static std::default_random_engine engine(std::random_device{}()); static std::uniform_int_distribution distribution(1,6); // [1,6] std::cout << distribution(engine) << “, “;

  1. // 测试randomInt
  2. for (auto i = 0; i < 100; i++) {
  3. std::cout << randomInt<1, 6>() << ", ";
  4. }
  5. return 0;

} ```