I need to generate a 4 digit random number in C++
I used the following code
#include<time.h>
int number;
number=rand()%1000;
srand ( time(NULL) );
but its doesn't gives a total rand开发者_开发技巧om number
number = rand() % 9000 + 1000;
There are 9000 four-digit numbers, right? Starting from 1000 till 9999. rand()
will return a random number from 0 to RAND_MAX
. rand() % 9000
will be from 0 to 8999 and rand() % 9000 + 1000;
will be from 1000 to 9999 . In general when you want a random number from a to b inclusive the formula is
rand() % (b - a + 1) + a
Also note that srand()
should be called only once and before any rand()
.
If you do consider the numbers between 0 an 999 inclusive to be "four digit numbers", simply use rand() % 10000
in that case. I don't consider them to be but I'm covering all bases, just in case.
HTH
Remember to call srand
only once.
Take a look at Boost.Random, if you don't like the distribution of rand
.
// produces randomness out of thin air
boost::mt19937 rng;
// distribution that maps to 1000..9999
boost::uniform_int<> fourdigits(1000,9999);
// glues randomness with mapping
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(rng, fourdigits);
// simulate rolling a die
int x = die();
You must seed your random generator srand
before calling rand()
#include<time.h>
srand( time(NULL) );
int number = rand() % 10000; // number between 0 and 9999
精彩评论