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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are 9000 four-digit numbers, right? Starting from 1000 till 9999.
rand()will return a random number from 0 toRAND_MAX.rand() % 9000will be from 0 to 8999 andrand() % 9000 + 1000;will be from 1000 to 9999 . In general when you want a random number from a to b inclusive the formula isAlso note that
srand()should be called only once and before anyrand().If you do consider the numbers between 0 an 999 inclusive to be “four digit numbers”, simply use
rand() % 10000in that case. I don’t consider them to be but I’m covering all bases, just in case.HTH