Function rand () does not return random numbers. C ++

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 number generated does not change, always being zero. Here is 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 could be wrong?

    
asked by anonymous 17.10.2016 / 20:09

1 answer

2

Have you put the 2 includes needed to generate the numbers? #include<stdlib.h> and #include<time.h> . The num_itens variable must have a value as well. Replace srand( (unsigned) time (NULL) ) with srand(time(0)) and place this line outside the loop ( do - while command) This solves your problem. Hugs

    
17.10.2016 / 21:08