-5

How do i get the random number generator in c to give me different numbers when ever my function is called.

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

int main() {

printf("%i",num());
printf("%i",num());

}
int num() {
    int MAX = 100;
    srand ( time(NULL));
    int num = rand() % MAX;
    return num;
}

No matter how many times i call the num function, it always prints the same number. How do i fix this so the number is different for every call.

user3593148
  • 505
  • 1
  • 3
  • 14
  • 3
    possible duplicate of [Problems when calling srand(time(NULL)) inside rollDice function](http://stackoverflow.com/questions/15570803/problems-when-calling-srandtimenull-inside-rolldice-function) – sashoalm Apr 09 '15 at 13:31

2 Answers2

7

The time function typically returns the time in second resolution, which means that if you call time(NULL) twice within one second then you will get the same result.

That will of course mean that you set the same starting seed to the random-number generator, which means the sequence will be the same.

You typically only call srand once, early in the main function.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
4

Move

srand ( time(NULL));

to main() . You need to call srand() once in main() and keep calling rand()

Gopi
  • 19,784
  • 4
  • 24
  • 36
  • 4
    Expanding on this... you're re-seeding the random number generator with the same value with each of your calls because relative to code execution, the value of `time()` does not change very often. By moving the seeding to happen only once, you eliminate this issue. – mah Apr 09 '15 at 13:30
  • Also, you should only seed a random number object once in a program as a "best practice". I am sure there are exceptions, but I can't think of any. – amalgamate Apr 09 '15 at 13:32