My output is 20 random 1\'s, not between 10 and 1, can anyone explain why this is happening?
#include
#include
#include <
(rand() % highest) + lowest + 1
You are generating a random number (ie (range*rand()/(RAND_MAX + 1.0))
) whose value is between -1 and 1 (]-1,1[
) and then casting it to an integer. The integer value of such number is always 0 so you end up with the lower + 0
EDIT: added the formula to make my answer clearer
random_integer = (rand() % 10) + 1
That should give you a pseudo-random number between 1 & 10.
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) << " ";
}
Probably "10 * rand()" is smaller than "RAND_MAX + 1.0", so the value of your calculation is 0.