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?
In modern c++ you may use the 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