0

I am trying to generate random numbers from 0 to 3 with the rand() function, and it works decently, but I have noticed something odd.

The function keeps producing the same pattern of numbers every time I run and rerun the project.

This is the code I am using broken down as simple as possible..

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
int randomNumber;

for (int i = 0; i < 15; i++)
{
    randomNumber = rand() % 4;
    printf("%d ", randomNumber);
}

getchar();
return 0;
}

And this prints 15 random numbers from 0 to 3, and for me this is what I get

1 3 2 0 1 0 2 2 2 0 1 1 1 3 1

So this is fine. But the issue is, every single time I run the program this exact same thing prints.

Any idea why this is happening?

brent_mb
  • 337
  • 1
  • 2
  • 14

1 Answers1

1

There is no such thing as a random number in computer science. Therefore to generate different outputs we must use pseudo-random. To do this write srand(time(0)) where you have declared your variables.

  • 1
    There are random numbers, practically and to the best of our knowledge. Some processors have built-in hardware to collect thermal noise and provide random data, and there are other techniques for gathering random data. – Eric Postpischil Feb 24 '19 at 00:10
  • I want a random number to be generated many times in a loop, doesn't `srand(time(0))` only work one time per run? – brent_mb Feb 24 '19 at 00:11
  • Eric, there is a difference between random and unpredictable –  Feb 24 '19 at 00:12
  • 1
    @TiborUkropina: As I wrote, to the best of our knowledge, we have both. – Eric Postpischil Feb 24 '19 at 00:12
  • @brent_mb, I ran the code and it worked fine for me... –  Feb 24 '19 at 00:14
  • @EricPostpischil that is true, just a debate for another time –  Feb 24 '19 at 00:17
  • @TiborUkropina did you run it multiple times? My issue is it continues to produce the same output. – brent_mb Feb 24 '19 at 00:17
  • @brent_mb I ran it 5 times and got different results each time, where are you running your code from? –  Feb 24 '19 at 00:18
  • 1
    @brent_mb Assuming you correctly called `srand()` **once** in your code, note that `time()` only has a resolution in seconds. If you rerun your program quickly you might be getting the same seed value (and the same random sequence). – Blastfurnace Feb 24 '19 at 00:21