【问题标题】:How can I set range to the random library如何将范围设置为随机库
【发布时间】:2019-07-21 17:40:24
【问题描述】:

我真的不喜欢 rand() 函数。我想使用该库,但我真的不知道如何设置一个范围,例如从 1 到 3。我想“随机”这些数字( 1,2,3) 而不是像 243245 这样的大数字。这段代码是您如何使用随机库并打印随机数的方法

#include <iostream>
#include <string>
#include <random>
using namespace std;
int main()
{
    minstd_rand simple_rand;

    simple_rand.seed(NULL);

    for (int ii = 0; ii < 10; ++ii)
    {
        std::cout << simple_rand() << '\n';
    }
}

【问题讨论】:

标签: c++ random numbers


【解决方案1】:

使用std::uniform_int_distribution:

#include <ctime>
#include <iostream>
#include <random>

int main()
{
    std::mt19937 rng(std::time(0)); // `std::minstd_rand` would also work.
    std::uniform_int_distribution d(1,3);

    for (int i = 0; i < 10; i++)
    {
        std::cout << d(rng) << '\n';
    }
}

【讨论】:

  • 非常感谢!它给了我一个错误,虽然“uniform_int_distribution d(1,3);”
  • 我发布了自己的答案
  • @Nope 这意味着您的编译器已过时,或者未配置为使用最新的 C++ 标准。
  • 这不是真的你忘记了但数字没有改变
  • @Nope 你不需要&lt;&gt;,因为 C++17。它对我有用。
【解决方案2】:
#include <iostream>
#include <random>
    int main()
    {
        std::random_device rd;  //Will be used to obtain a seed for the random number engine
        std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
        std::uniform_int_distribution<> dis(1, 3);

        for (int n=0; n<10; ++n)
            //Use dis to transform the random unsigned int generated by gen into an int in [1, 6]
            std::cout << dis(gen) << ' ';
        std::cout << '\n';
    }

感谢@holyBlackCat 致谢:cppreference.com

【讨论】:

  • 必须注意,虽然std::random_device 通常是首选的播种方法,但它不适用于 MinGW(即每次运行程序时都给出相同的结果)。
  • @HolyBlackCat 你是什么意思?代码不会一直输出相同的数字
  • 你在使用 MinGW 吗?
  • @HolyBlackCat 我猜不是
猜你喜欢
  • 2022-12-01
  • 1970-01-01
  • 2016-06-27
  • 1970-01-01
  • 2021-08-30
  • 2013-09-01
  • 1970-01-01
  • 2012-09-24
  • 2011-11-20
相关资源
最近更新 更多