Generating random number in C language

Asked

Viewed 774 times

2

Let’s assume I have an empty array of size 8.

int A[8];

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

So far I have that 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 calling it twice or more?

  • srand must be executed only once in the lifetime of the application, except when you want to generate the same sequence of random numbers or specific sequences, which is not your case. I didn’t see any answer say this explicitly. So normally, srand is called right at the startup of the application, within the main.

2 answers

3

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

example:

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

Translation of the 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 calling srand() with the same seed value.

2


Try to use the section 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.