Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++随机双值_C++ - Fatal编程技术网

C++随机双值

C++随机双值,c++,C++,如何创建介于.1和2.5之间的随机双精度 这就是我一直在尝试的 srand(time(NULL)); ((double) rand() / RAND_MAX) * 2.5 + .1 现代方法是使用随机数分布: #include <iostream> #include <random> using namespace std; int main() { random_device rd; mt19937_64 generator(rd());

如何创建介于.1和2.5之间的随机双精度

这就是我一直在尝试的

srand(time(NULL));

((double) rand() / RAND_MAX) * 2.5 + .1

现代方法是使用随机数分布:

#include <iostream>
#include <random>

using namespace std;

int main()
{
    random_device rd;
    mt19937_64 generator(rd());
    uniform_real_distribution<double> distribution(0.1, 2.5);
    for (int i = 0; i < 10; i++)
    {
        double d = distribution(generator);
        cout << d << endl;
    }
    return 0;
}

注意,0.1现代方法是使用随机数分布:

#include <iostream>
#include <random>

using namespace std;

int main()
{
    random_device rd;
    mt19937_64 generator(rd());
    uniform_real_distribution<double> distribution(0.1, 2.5);
    for (int i = 0; i < 10; i++)
    {
        double d = distribution(generator);
        cout << d << endl;
    }
    return 0;
}

请注意,0.1乘以2.4,范围2.5-.1而不是2.5。@Paulpro您应该将其作为答案发布。std::uniform_real_分布。乘以2.4,范围2.5-.1而不是2.5。@Paulpro您应该将其作为答案发布。std::uniform_real_分布。是的,使用std::rand真的是一种糟糕的做法。我不能走那么远。这在很大程度上取决于你需要那个随机数做什么。如果你需要快速且不介意脏,不要使用更昂贵的选项。有两个建议-1使用随机_设备作为种子。2,而不是Debug TyRead OngEngress,你不知道将会是什么,可能会像RAND一样糟糕,使用MT1937。一个关于RealthyDebug的警告:C++标准允许它过于简单地实现。确保您的工具链的库实现实际上是通过几个测试生成随机序列。使用std::random_设备的单个调用进行种子设定实际上是非常糟糕的,但是没有一个快速简单的解决方案。在某些情况下,std::random_设备是另一个具有固定种子的prng是的,使用std::rand确实是一个糟糕的做法。我不能走那么远。这在很大程度上取决于你需要那个随机数做什么。如果你需要快速且不介意脏,不要使用更昂贵的选项。有两个建议-1使用随机_设备作为种子。2,而不是Debug TyRead OngEngress,你不知道将会是什么,可能会像RAND一样糟糕,使用MT1937。一个关于RealthyDebug的警告:C++标准允许它过于简单地实现。确保您的工具链的库实现实际上是通过几个测试生成随机序列。使用std::random_设备的单个调用进行种子设定实际上是非常糟糕的,但是没有一个快速简单的解决方案。在某些情况下,std::random_设备是另一个具有固定种子的prng