Problem with random values

Asked

Viewed 83 times

1

Good night, you guys.

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

For this I made a function. It is almost all right, the number is generated and is transformed into letter. However, each 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 I have to, I’ll put the whole code.

Thank you very much

2 answers

2


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

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

To choose a specific list use srand() passing the number of the list you will 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 at each run of your program. Mainly don’t put the srand() within a cycle. The basic use is to put the srand(time(NULL)) on the principle of function main and from there, use always and only rand() times necessary to go through the list of pseudo-random numbers.

Your show would be then:

#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);
    }
    // ...
}
  • Now it is no longer repeating, however, it is presenting characters that I cannot present, such as special characters and lowercase letters. PS. I am not using

0

See my comments below. 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 parameter for x? It is not used in function!

[2] and [3] Assuming fila and fim_fila are correctly defined global variables You’ll never write in the first element of fila. fila begins with fila[0], but the value of fim_fila passes to 1 prior to assignment.

[4] Why you return the last generated random character?

[*] And still: the array fila needs a terminator to be a string. The last random letter should be followed by '\0'.

Get used to NOT USE global variables.

Browser other questions tagged

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