0

My problem is really simple. In C, I am trying to create a set of random values to set for r, however whenever I run the code it generates the same numbers over and over again rather than a unique sequence of numbers on every iteration. How should I change the code to fix this?

My code:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
int r;
for (int i;i<5;i++)
{
    r=rand() % 10;
    printf("%d\n",r);
}
}

This code always returns the values 1,7,4,0,9. How can I make it so that it instead randomizes each on every successive use of the function?

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70

1 Answers1

0

rand does not generate real random numbers. But to make the unique you need to seed it with something which will be different every time you run the program.

Example:

int main()
{
    int r;
    srand(time(NULL));  
    for (int i;i<5;i++)
    {
        r=rand() % 10;
        printf("%d\n",r);
    }
}
0___________
  • 60,014
  • 4
  • 34
  • 74
  • Thanks for the response, do you happen to know some seeds that will generate "randomer" numbers than using time, or where I might find some seeds? – Joseph Kant Nov 03 '20 at 15:45