-1

In C language, use srand (time (NULL)); can produce random numbers from 0 to 32767. My question is, why does NULL of srand (time (NULL)) give time () a random value?

Also, how to generate random numbers over 32767?

Use

if (rand ()% 2 == 0) {ans = rand () + (0b1 << 15);}
else {ans = rand ();}

Is it suitable?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • `srand (time (NULL)); can produce random numbers from 0 to 32767`.. `srand()` does not produce any value. – Sourav Ghosh Apr 13 '20 at 07:35
  • 3
    You don't use `srand` to generate random values; you use `rand()`. The `srand` function sets the seed value for the PRNG that feeds `rand()`. It would probably help to read the documentation of both [`srand()`](https://en.cppreference.com/w/c/numeric/random/srand), and [`rand()`](https://en.cppreference.com/w/c/numeric/random/rand), where the provided examples clearly tell you what `srand(time(NULL));` is actually doing. – WhozCraig Apr 13 '20 at 07:37

1 Answers1

0

Regarding "why does NULL of srand (time (NULL)) give time () a random value?"

Check the man page of time(), it mentions

time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). If t is non-NULL, the return value is also stored in the memory pointed to by t.

In this usage, we need only the return value, and we don't need to store that value additionally in any buffer, so we pass NULL as argument. Also, the returned value is not random, it's the number of seconds since the Epoch, 1970-01-01. So every invocation updates the value (strictly incremental).

That said, regarding the range of values returned by calling rand()

The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive (i.e., the mathematical range [0, RAND_MAX]).

Check the value of RAND_MAX in your platform.

That said, rand() is a poor PRNG, you can check this thread for better ways to get yourself a random number.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    *So every invocation updates the value (strictly incremental).* ... Not really, which means the value is not random at all. Running the program again during the same second will let it use the same pseudo-random sequence. `srand(clock())` is a much less problematic approach, although still poor for sensitive applications. – chqrlie Apr 13 '20 at 13:01