Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get instantaneous random number (in a loop)

I want to create fast new random number between 0 and 9. For this modified a code that I found there:
Why do I always get the same sequence of random numbers with rand()?
and integrated it into a loop

The output I get is

Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1

Instead I would like to get something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Random fast seeded: 2
Random fast seeded: 8
Random fast seeded: 4
Random fast seeded: 7
Random fast seeded: 3
Random fast seeded: 1
Random fast seeded: 3
Random fast seeded: 5
Random fast seeded: 1
Random fast seeded: 9

Here is the code


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


int main ()
{
  struct timespec ts;
  for (int i = 0; i<10; i++){
    clock_gettime(CLOCK_MONOTONIC, &ts);
    srand((unsigned int)ts.tv_nsec);
    printf ("Random fast seeded: %d\n", rand()%10);
  }
  return 0;
}

What am I doing wrong?

>Solution :

Place these two statements

clock_gettime(CLOCK_MONOTONIC, &ts);
srand((unsigned int)ts.tv_nsec);

before the for loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading