azi*_*ish 1 c++ random constructor class member-functions
我有一个类,其中还包括一个随机数引擎及其分布:
#include <iostream>
#include <cmath>
#include <random>
#include <chrono>
class C
{
public:
typedef std::mt19937_64 engine;
typedef std::uniform_real_distribution<double> distribution;
.
.
.
protected:
engine rng;
distribution dist;
void func();
.
.
.
};
Run Code Online (Sandbox Code Playgroud)
由于构造函数只被调用一次,我将种子放入其中:
C::C()
{ .
.
.
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
distribution dist(0.0, pow(10,12));
engine rng(seed);
}
Run Code Online (Sandbox Code Playgroud)
以下成员函数应该生成一个随机数,并且在程序的单次运行中将被多次调用:
void C::func()
{ .
.
.
double randNum = floor(dist(rng));
std::cout << randNum << std::endl;
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
但是,每次它生成数字0作为随机数.似乎dist(rng)没有做好自己的工作.
我真的需要找到问题并纠正输出.我将不胜感激任何帮助.
您可以在类中定义您的dist和eng变量
protected:
engine rng;
distribution dist; // Here
void func();
Run Code Online (Sandbox Code Playgroud)
在构造函数中,您可以使用相同的名称定义另一个
C::C()
{ .
.
.
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
distribution dist(0.0, pow(10,12)); // Here
engine rng(seed);
}
Run Code Online (Sandbox Code Playgroud)
我假设您希望后者是一个赋值,而不是一个新变量.然后你会得到你想要的数字.
C::C()
{ .
.
.
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
dist = distribution(0.0, pow(10,12)); // Here
rng = engine(seed);
}
Run Code Online (Sandbox Code Playgroud)
或者初始化
C() : dist(0.0, pow(10, 12)),
rng(std::chrono::system_clock::now().time_since_epoch().count())
Run Code Online (Sandbox Code Playgroud)