Range of random numbers in C

9

In a certain program, I need to generate a random value greater than 1000 (with a limit set by me for up to 5000 (maybe still a very high value)). This unique code refers to a type of registration to be performed. After solving some doubts of rand() % with a teacher, we arrive at this code: 1000 + rand() % rand() .

Would it be enough for what I want? And how could I demarcate it for up to 5000? This is the only part that I could not implement.

    
asked by anonymous 05.11.2014 / 01:09

3 answers

10

The rand () function generates pseudo-random numbers between 0 and (possibly) 32767 (depending on implementation may have greater breadth).

1001 + ( rand() % 4000 ) //os parenteses estão aí só para deixar a precedência mais visível

You say that you need a number greater than 1000, so the smallest possible number that the expression should generate is 1001. Since the rand() function is less than zero, just add 1001 to reach the lower limit considering that we are speaking of integers.

To ensure that there are no numbers out of range, we divide the result of the function by the number of possible elements in the range. If it goes from 1001 to 5000, we have 4000 possible numbers in the desired range. So the division by 4000 will pick up from 0 to 3999 inclusive.

See running on ideone .

    
05.11.2014 / 02:57
6

@Maniero Response Complement

The function void srand (unsigned int seed)

  • Each element of a pseudo-random sequence is generated from the previous element.
  • How it may be desirable to repeat a pseudo-random sequence in C always uses the same first element.
  • The void srand (unsigned int seed) function allows you to vary this first element, which serves as the seed of the sequence.

Using the clock as a seed

  • The time library has a time function whose result is a number of seconds elapsed since a fixed time (00:00:00 UTC January 1, 1970).

  • This number can be used as seed in the srand call to generate a variable and unpredictable seed.

      The result of time has a type time_t and must be converted to unsigned int so that it can be used as an argument to srand .

    • The time function also requires an argument that can be passed to the effect of this application as null

    • srando((unsigned) time(NULL))

Example:

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
   int numero_randomico;
   srand((unsigned) time(NULL));
   numero_randomico = 1001+(rand())%4000;
   ...
}
    
06.11.2014 / 12:13
4

To generate random integer values in C in the range [a, b) :

a + rand() % (b - a)

For example, x % 5 can be one of the 0, 1, 2, 3 or 4 values. So when we do rand() % (b - a) we will generate a number between 0 and b - a - 1 .

Representing at intervals:

[0, b - a - 1]

Now, if you add a to both ends of the range:

[a, b - 1]

What is the range you want (perhaps being careful to enter 1 at the far right).

    
05.11.2014 / 02:29