1

I'm using srand() to generate numbers from 0 to 3. My output is repeating the same combination of the four numbers and I'm not sure why or how to fix it.

#include <iostream>

int main(int argc, char** argv) {

  srand((unsigned int) time(NULL));
  
  for(int i = 0; i < 20; i++) {
    int n = std::rand() % 4;
    std::cout << n;
  }
  
  std::cout << std::endl;
  
  return 0;
}

Code output:

C:\School\ProgFund3\Int Stack>a
12301230123012301230

C:\School\ProgFund3\Int Stack>a
23012301230123012301

C:\School\ProgFund3\Int Stack>a
30123012301230123012

C:\School\ProgFund3\Int Stack>
r3mainer
  • 23,981
  • 3
  • 51
  • 88
That Guy
  • 11
  • 1
  • [Please please don't post images of text.](https://meta.stackoverflow.com/q/285551/1679849) – r3mainer Sep 23 '22 at 08:08
  • if you can use the `random` header instead you'd get access to much better PRNGs and associated algorithms, e.g. see https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution#Example – Sam Mason Sep 23 '22 at 13:27

0 Answers0