Pergunta

I am trying to get two random numbers in a row with C:

#include <time.h>
#include <stdlib.h>
void testcollgenarray() {
    for(int i=0; i<10; i++)
    {
        int r1 = rand() % 256;
        int r2 = rand() % 256;
        cout << r1 << endl;
        cout << r1 << endl;
    }
}

Apparently, in each loop the random number generator is outputing the same number:

207
207
41
41
98
98
49
49
6
6
8
8
95
95
79
79
154
154
252
252
Foi útil?

Solução

    cout << r1 << endl;
    cout << r1 << endl;
    //       ^-- You're printing r1 twice

Outras dicas

You should give seed to your random generation. For example use this line of code once before your random generation:

srand(time(0));

Which uses current time for random generation.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top