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?
The
srand
should be called only once at the beginning of the program, not within the loopingdo
. Related: Generating random number in C language– Gomiero
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.
– TNT