0

I am trying to learn basic C, and I'm running into a problem. Why does my code return the same number every time?

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

int randomNum(int min, int max){
 srand(time(NULL));
 return min + (rand() % ((max-min)+1));
}

int main(void) {

    printf("%i",randomNum(0,2));
    printf("%i",randomNum(0,2));
    printf("%i",randomNum(0,2));
    printf("%i",randomNum(0,2));
  
  return 0;
}
  • To summarize the suggested duplicate: The current time doesn't change (at the resolution of the system clock) between your four calls, so the same seed is being used each time. – Adrian Mole Oct 06 '21 at 16:46
  • 2
    `srand()` initializes the PRNG with the initial state. Calling it before each `rand()` call is not its intended usage. – jxh Oct 06 '21 at 16:47

0 Answers0