Random float number generation

后端 未结 14 1586
孤城傲影
孤城傲影 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:38

    In modern c++ you may use the header that came with c++11.
    To get random float's you can use std::uniform_real_distribution<>.

    You can use a function to generate the numbers and if you don't want the numbers to be the same all the time, set the engine and distribution to be static.
    Example:

    float get_random()
    {
        static std::default_random_engine e;
        static std::uniform_real_distribution<> dis(0, 1); // rage 0 - 1
        return dis(e);
    }
    

    It's ideal to place the float's in a container such as std::vector:

    int main()
    {
        std::vector nums;
        for (int i{}; i != 5; ++i) // Generate 5 random floats
            nums.emplace_back(get_random());
    
        for (const auto& i : nums) std::cout << i << " ";
    }
    

    Example output:

    0.0518757 0.969106 0.0985112 0.0895674 0.895542
    

提交回复
热议问题