Problem with random values

1

Good evening, guys.

I am solving an exercise where I must, at each execution, generate a random number and then turn it into letter.

For this I made a function. It is almost all right, the number is generated and is transformed into letter. However, every time I run the program, it always gives the same sequence of numbers / characters. That is, it is not random.

The function code is:

int inserir_fila(int x)
{
char ch;
if (fim_fila<=MAX)
    {
        x= rand()% 26;
        ch= x + 'A';
        fim_fila++;
        fila[fim_fila]=ch;
    }
     else
      {
        printf("Fila Cheia!\n");
      }
 return(x);
}

If you need, put the whole code.

Thank you very much

    
asked by anonymous 15.04.2015 / 07:24

2 answers

2

The rand() function fetches a number from a fixed list of random numbers.

If you do not choose a specific list, C uses list # 1.

To choose a specific list, use srand() by passing the number of the list you are going to use.

srand(1);          // usa lista #1
srand(42);         // usa lista #42
srand(1234567);    // usa lista #1,234,567
srand(time(NULL)); // usa lista #(numero de segundos desde 1970-01-01)

Note that you should only specify the list to use once in each run of your program. You do not mainly put srand() into a cycle. The basic use is to put srand(time(NULL)) at the beginning of the function main and from there, always use and only rand() the times necessary to go through the list of pseudorandom numbers.

Your program would look like this:

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

int main(void) {
    srand(time(NULL)); // especificar lista de numeros aleatorios
    // ...
    for (int k = 0; k < 100; k++) {
        inserir_fila(k);
    }
    // ...
}
    
15.04.2015 / 10:36
0

See my comments below. The comments relate to the lines marked

int inserir_fila(int x)      // [1]
{
char ch;
if (fim_fila<=MAX)
    {
        x= rand()% 26;
        ch= x + 'A';
        fim_fila++;          // [2]
        fila[fim_fila]=ch;   // [3]
    }
     else
      {
        printf("Fila Cheia!\n");
      }
 return(x);                  // [4]
}

[1] What is the x parameter used for? It is not used in the function!

[2] and [3] Assuming that fila and fim_fila are correctly defined global variables You will never write to the first element of fila . fila starts with fila[0] , but the value of fim_fila becomes 1 before assignment.

[4] What is the purpose of returning the last random character generated?

[*] And yet: the fila array needs a terminator to be a string. The last random letter should be followed by '%code%' .

Get used to NOT USE global variables.

    
15.04.2015 / 20:50