C++ generating random numbers
Because, on your platform, RAND_MAX == INT_MAX
.
The expression range*rand()
can never take on a value greater than INT_MAX
. If the mathematical expression is greater than INT_MAX
, then integer overflow reduces it to a number between INT_MIN
and INT_MAX
. Dividing that by RAND_MAX
will always yield zero.
Try this expression:
random_integer = lowest+int(range*(rand()/(RAND_MAX + 1.0)))
It's much easier to use the <random>
library correctly than rand
(assuming you're familiar enough with C++ that the syntax doesn't throw you).
#include <random>
#include <iostream>
int main() {
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 eng(seed);
std::uniform_int_distribution<> dist(1, 10);
for(int i = 0; i < 20; ++i)
std::cout << dist(eng) << " ";
}