当前位置:   article > 正文

C++随机数生成器mt19937生成随机数的用法_c++ mt19937

c++ mt19937
  1. #include <iostream>
  2. #include <chrono>
  3. #include <random>
  4. int main()
  5. {
  6. // obtain a seed from the system clock:
  7. unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
  8. std::mt19937 generator(seed); // mt19937 is a standard mersenne_twister_engine
  9. auto number = generator();//生成一个随机数
  10. std::cout << "Random value: " << number << std::endl;
  11. return 0;
  12. }

输出:

Random value: 3878294182

下面的代码来自官方示例

  1. // mersenne_twister_engine constructor
  2. #include <iostream>
  3. #include <chrono>
  4. #include <random>
  5. #include <string>
  6. using namespace std;
  7. int main()
  8. {
  9. // obtain a seed from the system clock:
  10. unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();
  11. // obtain a seed from the user:
  12. std::string str;
  13. std::cout << "Please, enter a seed: ";
  14. std::getline(std::cin, str);
  15. std::seed_seq seed2(str.begin(), str.end());
  16. std::mt19937 g1(seed1); // mt19937 is a standard mersenne_twister_engine
  17. std::cout << "A time seed produced: " << g1() << std::endl;
  18. std::cout << typeid(g1()).name() << endl;
  19. std::mt19937 g2(seed2);
  20. std::cout << "Your seed produced: " << g2() << std::endl;
  21. return 0;
  22. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/966615
推荐阅读
相关标签
  

闽ICP备14008679号