How to generate random number?
-
I want to generate a random number between a specified range of 1 to 100, how can I do this? Thanks in advance, Dave :-D
"The man who reads nothing is better educated than the man who reads nothing but newspapers."- Thomas Jefferson
Technically, you can't generate a truly random number. You can, however, get pseudo-random numbers using
rand()
. For your specific range, try:int x = (rand() % 100) + 1;
You may or may not also want to use
srand()
, which seeds the algorithm. -
Technically, you can't generate a truly random number. You can, however, get pseudo-random numbers using
rand()
. For your specific range, try:int x = (rand() % 100) + 1;
You may or may not also want to use
srand()
, which seeds the algorithm. -
Thanks, I'll give it a try. :-D
"The man who reads nothing is better educated than the man who reads nothing but newspapers."- Thomas Jefferson
You'd better initialize the seed first. Use srand(time(NULL)). Otherwise you will always get the same random number sequence.
-
You'd better initialize the seed first. Use srand(time(NULL)). Otherwise you will always get the same random number sequence.
Which is not necessarily a bad thing, especially when trying to reproduce a problem.