0

Despite seeding the rand() every time I call the two functions, they always repeat the same output

#include <iostream>
#include <cstdlib>
#include <unistd.h>
using namespace std;



void test1(){
 srand(time(0));
 int i = rand()%10;
 cout << i << endl;
}
void test2(){
 srand(time(NULL));
 int l = rand()%10;
 cout << l << endl;
}

int main(){
  test1();
  test2();

 return 0;
}

output: 0 0

output 2: 4 4

output 3: 1 1

Any help would be greatly appreciated!

user17732522
  • 53,019
  • 2
  • 56
  • 105
  • `time(0)` returns the same value for up to a second so if your code takes less than a second to execute you'll probably seed with the same number every time – Alan Birtles Feb 26 '22 at 08:13
  • Usually `srand` is called only once by a program, shortly after the start of `main`. – Eljay Feb 26 '22 at 13:33
  • The title is wrong. Should be "multiple `rand()` functions repeat the same output **because of** seeding". – Pete Becker Feb 26 '22 at 14:27

0 Answers0