generate a random number between 1 and 10 in c

#include <stdio.h> #include <stdlib.h> int main() { int randomnumber; randomnumber = rand() % 10; printf("%d\n", randomnumber); return 0; } 

This is a simple program where randomnumber is an uninitialized int variable that is meant to be printed as a random number between 1 and 10. However, it always prints the same number whenever I run over and over again. Can somebody please help and tell me why this is happening? Thank you.

5

5 Answers

You need a different seed at every execution.

You can start to call at the beginning of your program:

srand(time(NULL)); 

Note that % 10 yields a result from 0 to 9 and not from 1 to 10: just add 1 to your % expression to get 1 to 10.

7
srand(time(NULL)); int nRandonNumber = rand()%((nMax+1)-nMin) + nMin; printf("%d\n",nRandonNumber); 

Here is a ready to run source code for random number generator using c taken from this site: . The implementation here is more general (a function that gets 3 parameters: min,max and number of random numbers to generate)

#include <time.h> #include <stdlib.h> #include <stdio.h> // the random function void RandomNumberGenerator(const int nMin, const int nMax, const int nNumOfNumsToGenerate) { int nRandonNumber = 0; for (int i = 0; i < nNumOfNumsToGenerate; i++) { nRandonNumber = rand()%(nMax-nMin) + nMin; printf("%d ", nRandonNumber); } printf("\n"); } void main() { srand(time(NULL)); RandomNumberGenerator(1,70,5); } 
0

You need to seed the random number generator, from man 3 rand

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

and

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

e.g.

srand(time(NULL)); 
0

Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.

Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid()) (_getpid() on Windows), but that still won't be random.

The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random (Linux) or CryptGenRandom() (Windows), or from a service like random.org.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like