cout << r1 << endl;
cout << r1 << endl;
// ^-- You're printing r1 twice
Generate two random numbers in a row won't work in C? [closed]
Domanda
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
Soluzione
Altri suggerimenti
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.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow