+ 2

Random floats in C++

How can I get a random number between, say, 1.001 and 2.999?

27th Mar 2017, 11:10 PM
Jeremy Hunter
Jeremy Hunter - avatar
7 Respostas
+ 6
Generally you initialize the seed using the current time. Here's a full example: #include <iostream> #include <random> #include <ctime> float random_float(float min, float max) { return ((float)rand() / RAND_MAX) * (max - min) + min; } int main() { srand(time(NULL)); // Print 100 random floats between 1.001 and 2.999. for (int i = 0; i < 100; ++i) std::cout << random_float(1.001f, 2.999f) << std::endl; return 0; }
28th Mar 2017, 1:46 AM
Squidy
Squidy - avatar
+ 6
My approach is: float random_float(float min, float max) { return ((float)rand() / RAND_MAX) * (max - min) + min; } Then you can call it like: random_float(1.001f, 2.999f); Of course, make sure to include <random> and initialize the seed with srand.
27th Mar 2017, 11:17 PM
Squidy
Squidy - avatar
+ 3
how do I initialize the seed? Also can you give an example?
27th Mar 2017, 11:34 PM
Jeremy Hunter
Jeremy Hunter - avatar
+ 3
great, thanks!
28th Mar 2017, 5:30 AM
Jeremy Hunter
Jeremy Hunter - avatar
+ 3
What is RAND_MAX? Is that a constant value from random library?
11th Jul 2017, 6:40 AM
Karuntos
Karuntos - avatar
0
I can't understand. Have any easy way it's more than ?
15th Nov 2019, 4:27 PM
Lee Abid
Lee Abid - avatar
0
I can't understand. Have any easy way it's more than ?
15th Nov 2019, 4:27 PM
Lee Abid
Lee Abid - avatar