0

Hello i'm trying to understand this issue: I need to write a function which should return two different random integers but i didn't manage to get two outputs from function so i decided to simple call 2 times the same function by doing this

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

 int query ();

 int query (){
     int c,d;
     srand(time(NULL));

    c = 1 + (rand() % 9);
    //d = 1 + (rand() % 9); 

    //printf("How much is %d times %d?\n", c, d);



}

int main (){

    int firstNumber, secondNumber;

        firstNumber= query();
        secondNumber = query();

        printf("How much is %d times %d ?\n", firstNumber, secondNumber);
        //query();
}

but sadly the number i get running the program is the same (firstNumber == secondNumber). BUT when i uncomment the lines in the function and line //query() in main then i get two different random numbers. I'm trying to understand why so if someone could help i'll appreciate it. thanks.

  • It's because the time in seconds probably doesn't change between the two calls to `srand`. You should only call `srand` once in your program. – Ian Abbott Jun 23 '17 at 15:42
  • you need to move srand(time(NULL)); to main function – Ivan Sheihets Jun 23 '17 at 15:52
  • @IvanSheigets your advice works and thanks for that, but i don't get where is the difference by having srand to main function, when i call the function query() in order to get two numbers, i'm also calling srand(time(NULL)) at two different time, or not? – entropic.chaos Jun 23 '17 at 17:30

0 Answers0