Generating random number in C language

2

Let's say I have an empty array of size 8.

int A[8];

And so I intend to populate it with random values whose I would have a function similar to rand(); However, I call rand() for each element of the array, so all elements have the same value.

So far I have this function:

int randInt(int intMax)
{
    srand(time(NULL));
    return rand() % (intMax+1);
}

In case it would return the same value if I called this function two or more times, because it is related to time. My question would be how can I implement a function that returns a random value even by calling it two or more times?

    
asked by anonymous 20.05.2015 / 00:42

2 answers

2

Try using the snippet below

int rand[8];
int range;
srand(time(NULL));
range = (1000 - 1) + 1; 

for(int i = 0; i < 8; i++)
{
  rand[i] = rand() % range + 1;
}
    
20.05.2015 / 00:49
3

Use the srand(time(NULL)); function before calling the rand function, it serves to reload the values that will be generated by the rand.

example:

srand(time(NULL));
for(int i = 0; i < 8; i++)
{
  rand[i] = rand() % range + 1;
}

Translation of function description

  

The srand () function defines 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.

    
20.05.2015 / 05:25