# Thread: rand() function giving same number repeatedly

1. ## rand() function giving same number repeatedly

Hello everyone. I'm having a bit of a problem getting my probability program to work. It's supposed to determine the probability that 13 will be achieved with 3 dice rolls but every die gets the same value.

Here is the code:

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int rand_int(int,int);
int a=1, b=6;

main()
{
int die[100], n=0, i, dietot=0, l;
double prob;

for(i=0;i<100;i++)
{
die[i]=rand_int(1,6);
printf("\nDie %d = %d",i+1,die[i]);
dietot=dietot+die[i];
if(dietot==13)n++;
l=i%3;
if(l==0)dietot=0;
}
prob=n/100;
printf("\nThe probability of throwing 3 dice and getting 13 is %lf out of 100",prob);
}

int rand_int(int a, int b)
{
srand(time(0)); //takes the current system time as a seed number
return (a + rand()%(b-a+1));
}```
I'm really at a loss as to why this code won't work. My seed should give a different random number each time the loop calls rand_int but I just get 100 identical dice...

Any help would be greatly appreciated!

2. You should just seed the PRNG once. What is probably happening now is that time(0) is being called 100 times, and since all 100 calls happen within the same second, the result of time(0) is the same, thus the first number in the PRNG sequence is the same. If you only seeded the PRNG once, you would actually get to use the first 100 numbers in the sequence.

3. Thanks very much laserlight! Put the srand() in to the main program before the loop and it now works perfectly. I'll have to complain to my lecturer because he defined rand_int like this:

Code:
```int rand_int(int a,int b)
{
srand( (unsigned)time( NULL ) );
return rand()%(b-a+1) + a;
}```
Thanks again!

Popular pages Recent additions