How do you get a random number in c++?
Printable View
How do you get a random number in c++?
rand() returns a number between 0 and RAND_MAX (depends on your computer).Code:#include <cstdlib>
#include <ctime>
// at start of program
std::srand(time(NULL))
// when needed
int num = std::rand();
Code:int i;
srand(10); // 10 is an integer value - a seed can be anything
// or you can leave it null
for(i=0;i<10;i++) printf("%d\n",rand() ); // print some random numbers
thanks, but what i really need to know is how to get random numbers between two parameters, like a random number between 0 and 10
that would be
std::rand()%11
for any two numbers
a+std::rand()%(b+1)
For any two numbers it would be
a+(std::rand()%(b-a))
This means including a but excluding b.
And not all standard libraries have the identifiers of the <c*> headers in the std namespace. I think VC++6 for example doesn't.
Then the compiler is wrong. It's not our job to pander to broken implementations ;)
Just wanted to mention it. We know that the implementation of VC++6 is very broken.
And of course you have to watch out for macros, they won't ever be in any namespace.