Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Generating a 4 digit random number

Tags:

c++

visual-c++

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

like image 759
Sudantha Avatar asked Nov 27 '22 23:11

Sudantha


1 Answers

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

like image 101
Armen Tsirunyan Avatar answered Dec 05 '22 08:12

Armen Tsirunyan