+ 2
Random floats in C++
How can I get a random number between, say, 1.001 and 2.999?
7 Antworten
+ 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;
}
+ 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.
+ 3
how do I initialize the seed? Also can you give an example?
+ 3
great, thanks!
+ 3
What is RAND_MAX? Is that a constant value from random library?
0
I can't understand. Have any easy way it's more than ?
0
I can't understand. Have any easy way it's more than ?