0

Trying to create a function that generates a random number using rand() and srand().

This code prints 3 random numbers successfully:

//prints a random number from 1 to 10 3 times.
void main()
{
    int num;
    srand(time(NULL));
    num = rand() % 10;
    printf("%d\n", num);
    num = rand() % 10;
    printf("%d\n", num);
    num = rand() % 10;
    printf("%d\n", num);
}

//Output: 3 5 6

This code using a function doesn't:

//calls PrintRandomNumber 3 times.
void main()
    {
        int i=0, num;
        for(i=0; i<3; i++)
        {
        printRandomNumber(0, 10);
        }
    }

//Prints a random numberin the range of lowestValue to highestValue.
void printRandomNumber(int lowestValue, int highestValue)
{
    int randomNumber = 0;
    srand(time(NULL));
    randomNumber = (rand() % (highestValue - lowestValue + 1)) + lowestValue;
    printf("%d\n", randomNumber);
}
//Output: 3 3 3

The problem is calling srand(time(NULL)) multiple times.

Can a function print/return a random number using rand() and srand() without having to call srand(time(NULL)) in the main?

Bar Yeyni
  • 1
  • 2
  • 2
    Just call `srand(time(NULL));` ***once*** - from `main`, before you do anything else. – Adrian Mole Aug 22 '21 at 19:32
  • ... the problem is because your three function calls are run so quickly after each other that the current time doesn't change, and you get the same seed each time. – Adrian Mole Aug 22 '21 at 19:33
  • To answer your last (edited-in) point - yes, you can. Just use something else as the argument for `srand()`, or wait between calls. – Adrian Mole Aug 22 '21 at 19:38

1 Answers1

0

You can to do that as in the example below:

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

int main () {
   int i, n;
   time_t t;
   
   n = 3;
   
   /* Intializes random number generator */
   srand((unsigned) time(&t));

   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 10);
   }
   
   return(0);
}
Roman Kagan
  • 10,440
  • 26
  • 86
  • 126