I do know python and it is so simple to create a random number on a set interval but then in C it is a little more complicated it seems. So here is what I have by looking at other questions on stack overflow.
int diceroll_1;
diceroll_1=(rand()%3)+1;
printf("%d\n",diceroll_1);
The problem is that it gives me 3 every time. I want it to be different every time the program is compiled and run. I want it to be from 1 to 3 random. My understanding is that this might save it and that is why it is generating 3 every time and not what I want. How do I generate a random number every time and not the same number?
The
rand
function works by taking the previous random number generated, performing some permutation on it, then returning that. If it's the first time callingrand
, it will take the value of the seed for the random number generation sequence and permute that.Remember that computers are fundamentally deterministic machines and "randomness" doesn't really exist at the hardware/CPU instruction level barring newfangled devices like TRNGs.
High level languages like Python may hide this from you and take care of seeding the random number generation to the system time automatically, behind the scenes, but C will not. You need to call
srand
with a seed value before callingrand
.Now, calling
srand
with arguments likesrand(3);
andsrand(100);
will generate different random numbers from each other, they will be the same sequence each time. If you want a truly unique value for the seed, try using the current system time:srand((unsigned)time(NULL));
Did you seed
srand
? If not, try like this:Output:
PS:
rand()
produces pseudorandom numbers, as our prof. in IP insisted! It needs to be seeded, otherwise it will give the same numbers again and again, since from the ref we have that: