0

My rng code for some reason reproduces only one number if it repeats in one second.

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

int main() {
  for(int i = 1; i <= 100 / 2 ; i++) {
    int now = (int) time(NULL);
    srand(now);
    int rng = rand() % 100 +1;
    printf("%d ", rng);
  }
}

This will produce this (number is random every second):

86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86 86

Do you know what is wrong? Thank you in advance. :)

Fajn
  • 11
  • 7
  • 1
    Call `srand` only once (before the loop) – David Ranieri Oct 13 '20 at 06:09
  • I am a fool! Thank you very much I was staring at it for like half an hour and was not able to figure out why it was not working. How do I close this question or how do I mark your comment as answer? – Fajn Oct 13 '20 at 06:12
  • You are welcome, don't worry for that, let me find a duplicated. – David Ranieri Oct 13 '20 at 06:14
  • ```time``` return number of seconds (which is used to feed PRNG) since epoch calling time in a loop doesn't cause time to change unless one second is passed from what i see you either need to increase number of loops or better call ```sleep``` at start of loop and don't forget to flush cache ofcourse (add '\n') – KMG Oct 13 '20 at 06:14
  • @KhaledGaber Although this is true, it will extremely slow down the working of the program. In my case I need numbers as fast as the PC can count them. Still thanks. – Fajn Oct 13 '20 at 06:28
  • @Fajn you are right but it will be more secure although if security is a big concern you shouldn't use these and read from ```urandom``` if using linux. which is much more secure to get random numbers. – KMG Oct 13 '20 at 06:34

1 Answers1

2

Seed the rand() function before the for loop:

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

int main() {
  srand(time(NULL));
  for(int i = 1; i <= 100 / 2 ; i++) {
    int rng = rand() % 100 +1;
    printf("%d ", rng);
  }
  return 0;
}
Shubham
  • 1,153
  • 8
  • 20