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

int main( void){

    int x = rand()%100;
    printf("%d\n", x);
    return 0;
}

The code above generates a random number correctly. Is this correct? But, other sources always include library and srand(time(NULL)). Why do we have to include include library and srand(time(NULL))? Are there any reasons to include?

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

int main( void){
    srand(time(NULL));
    int x = rand()%100;
    printf("%d\n", x);
    return 0;
}
aizhan_maksatbek
  • 69
  • 1
  • 1
  • 9
  • 1
    In the first case it is always the *same* random number each time you run the program. The second case "seeds" the RNG. – Weather Vane Oct 14 '18 at 09:45

3 Answers3

3

Because if you run this code many times, you will get the same result! (also, rand() return the same result in each run). Hence, you can initialize the seed of random in each run of the code to get a different random result by srand. Using time(NULL) to set a different seed of random through srand.

OmG
  • 18,337
  • 10
  • 57
  • 90
0

srand is a random number generator function which will randomize the number produced by rand function.

haccks
  • 104,019
  • 25
  • 176
  • 264
0

Imagine you have a (huge) library with (huge) books filled with (apparently random, but fixed) numbers.

When you do rand() you get the current number on the current book and advance to the next.

When you do srand(<number>) you select the book rand() will use from that point forward.

time(NULL) return the number (after conversion) of seconds since about midnight 1970-01-01. That number changes every second, so using that number to "select a book" pretty much guarantees a new sequence of "random" numbers every time your program runs.

If you don't select a book, the rand() function takes numbers from book #1 (same as srand(1)).

Having fixed random numbers may be useful in certain situations. For example, you want to test different functions with the same data.

pmg
  • 106,608
  • 13
  • 126
  • 198