에디의 우당탕탕 코딩공장

[객체지향프로그래밍(2)] rand()와 srand()의 차이

by 인턴 에디

1. rand( ) 👉 int rand(void)

Returns a pseudo-random integral number in the range between 0 and RAND_MAX.

 

This number is gererated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.

v1 = rand() % 100;         // v1 in the range 0 to 99
v2 = rand() % 100 + 1;     // v2 in the range 1 to 100
v3 = rand() % 30 + 1985;   // v3 in the range 1985-2014

RAND_MAX

This macro ecpands to an integral constant expression whose value is the maximum value returnded by the rand function.

This value library(<stdlib>)-dependent, but os guaranteed to be at least 32767 an any standard library implemetation.

32767 ≒ 2^16 ≒ 2^10 * 2^6 ≒ 64 * 1Kilo ≒ 64K ≒ 65536 range(-32768~32768)

 

🙋‍♀️But, If we use this, the random number sequence out samely all the time!

   👉 because, this rand func print from there "seed number" as has certain sequence.

So, we have to set this sequence. if you want to print out as different random numbers.

 

2. srand(unsigned int seed); 👉 Setting seed number

If the seed is different with each other, the random numbers creat differently.

 

3. unsigned int seed = time(nullptr);

time(nullptr) is a Unix TimeStamp. We can know the time passed after we started program.

 

/* srand example */
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  printf ("First number: %d\n", rand()%100);
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  printf ("Again the first number: %d\n", rand()%100);

  return 0;
}

블로그의 정보

에디의 우당탕탕 코딩 공장

인턴 에디

활동하기