The following code outputs a random number each second:
int main () { srand(time(NULL)); // Seeds number generator with execution time. while (true) { int rawRand = rand(); std::cout << rawRand << std::endl; sleep(1); } }
How might I size these numbers down so they're always in the range of 0-100?
For example, rand() % 6 will produce a random number between 0 and 5. Scaling a random number as an integer value between 1 and N may be accomplished by using the expression rand() % N + 1 or 1 + rand() % N. For example, 1 + rand() % 6 will produce a random number between 1 and 6.
The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.
Expands to an integer constant expression equal to the maximum value returned by the function std::rand.
The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX.
If you are using C++ and are concerned about good distribution you can use TR1 C++11 <random>
.
#include <random> std::random_device rseed; std::mt19937 rgen(rseed()); // mersenne_twister std::uniform_int_distribution<int> idist(0,100); // [0,100] std::cout << idist(rgen) << std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With