问题
int main()
{
srand((unsigned)time(0));
int random_integer;
int lowest=0, highest=10;
int range=(highest-lowest)+1;
for(int index=0; index<20; index++){
random_integer = (rand() % range) + lowest/(RAND_MAX + 1.0);
cout << random_integer << endl;
}
}
I am getting the output from 0 to 10, 11 numbers, but I don't want to get number 10, just numbers 0 to 9, that means 10 random numbers, what should I do?
回答1:
Modulo operation x % c;
returns the remainder of division of number x
by c
. If you do x % 10
then there are 10
possible return values: 0 1 2 3 4 5 6 7 8 9
.
Note that generating random numbers by using rand()
with %
produces skewed results and those numbers are not uniformly distributed.
Here's the simple C-style function that generates random number from the interval from min
to max
, inclusive:
int irand(int min, int max) {
return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
}
Note, that numbers generated by this functions are uniformly distributed:
int occurences[8] = {0};
srand(time(0));
for (int i = 0; i < 100000; ++i)
++occurences[irand(1,7)];
for (int i = 1; i <= 7; ++i)
cout << occurences[i] << ' ';
output: 14253 14481 14210 14029 14289 14503 14235
Also have a look at:
Generate a random number within range?
Generate random numbers uniformly over an entire range
What is the best way to generate random numbers in C++?
回答2:
It appears that you need to fully understand, then modify this line
random_integer = (rand() % range) + lowest/(RAND_MAX + 1.0);
回答3:
rand() % 10
normally does the trick for me.. (unless I'm missing something)
回答4:
int main()
{
srand((unsigned)time(0));
int random_integer;
int lowest=0, highest=9;
int range=(highest-lowest)+1;
for(int index=0; index<20; index++){
random_integer = (rand() % range) + lowest;
cout << random_integer << endl;
}
}
回答5:
this type of questions have been answered n number of times.
have a look at this
来源:https://stackoverflow.com/questions/9515572/c-generating-random-numbers-1