#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.
And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator. srand(time(0)); // Initialize random number generator.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With