Rand() function does not return random numbers. C++

Asked

Viewed 1,204 times

1

I have a function that needs to generate, in a specific part, a random number to do a certain task. But whenever the program enters this function, the generated number does not change, always being zero. Follow the code:

do{ // Garante que seja escolhido um item que ainda nao esteja na mochila
        srand( (unsigned) time (NULL) );    // Gera um numero aleatorio, usado para selecionar um item qualquer na lista de itens disponiveis
        item_position = rand() % num_items;
        printf("item_position: %d", item_position);

        j = 0;
        while(j < index_items->size()) 
        {
            printf("Item escolhido: %d \n\n\n", item_position);
            if(item_position == index_items->at(j)) // Verifica se o item escolhido aleatoriamente ja nao esta na mochila
                itens_repetidos += 1;               //Dessa forma, evita repeticoes dentro da mochila
            j++;
        }
    }while(itens_repetidos != 0);

As seen in the code, I use the srand and Rand functions to generate the number. What may be wrong?

  • 2

    The srand should be called only once at the beginning of the program, not within the looping do. Related: Generating random number in C language

  • I suggest generating some random numbers and confirming whether the Rand() function returns a value between 0 and 1 or integer. I agree with @Gomiero, use srand only to boot, only 1x in the program.

1 answer

2


You have put the 2 necessary includes to generate the numbers? #include<stdlib.h> and #include<time.h>. The variable num_items must have a value as well. Replace the srand( (unsigned) time (NULL) ) for srand(time(0)) and put this line outside the loop (command do - while) That solves your problem. Hug

Browser other questions tagged

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