Question

[Solved] C++ Generating a 4 digit random number

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 random number

Enquirer: Sudantha

||

Solution #1:

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

Respondent: Armen Tsirunyan

Solution #2:

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();
Respondent: dalle

Solution #3:

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
Respondent: log0

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy