Random float number generation

后端 未结 14 1588
孤城傲影
孤城傲影 2020-11-22 05:05

How do I generate random floats in C++?

I thought I could take the integer rand and divide it by something, would that be adequate enough?

14条回答
  •  独厮守ぢ
    2020-11-22 05:30

    Take a look at Boost.Random. You could do something like this:

    float gen_random_float(float min, float max)
    {
        boost::mt19937 rng;
        boost::uniform_real u(min, max);
        boost::variate_generator > gen(rng, u);
        return gen();
    }
    

    Play around, you might do better passing the same mt19937 object around instead of constructing a new one every time, but hopefully you get the idea.

提交回复
热议问题