2
When I was studying pseudocode, I learned that when you call a function and create a variable, it only "exists" when I call that function, for example.
funcao teste():
x = 10
retorna x
In case, when I called my test function, it would create the variable x
, and after she returned he would erase.
I’m studying C++ and tried to do this function to generate random numbers.
int gerar_numeros() {
srand(time(NULL));
int x = rand() % 100;
return x;
}
and to assign this part in the function to the vector main()
.
for (int c = 0; c <= 10; c++)
{
vetor[c] = gerar_numeros();
}
But the problem is he only changed the numbers when I ran the script again, for example, the first time the all values of the vector was 5, the second time 10 and so on, so I changed the logic to this one and it worked.
void gerar_numeros(int vetor[]) {
srand(time(NULL));
//int x = 1 + rand() % 100;
for (int c = 0; c <= 10; c++)
{
vetor[c] = rand() % 100;
}
In that logic from above is as if the variable x
was stored in memory, and so always returns the same number.
Got it, the problem is that I was starting srand() every time I called the right function? Thanks!!
– zaque
@Zaque Sim
srand
sets the starting point of random generation. If you always set the same starting point before generating a number then always generate the same number.– Isac
To be more complete, the problem is not so much that called
srand()
several times, because it is giving a seed oftime(NULL)
, that changes. The problem is that calledsrand()
several times very fast. The code is completing beforetime(NULL)
change in value. If you run the original code to generate many more numbers (maybe 100000), it will result in many numbers of the same value followed by many numbers of another value.– Kyle A