언어/C&C++ 응용

[C] 난수 발생

차가운오미자 2021. 8. 3. 20:38

int rand(void)

는  C에서 기본적으로 제공되는 난수발생 함수이다. 

0부터 RAND_MAX 까지의 수 중에 난수가 발생한다. 

 

이 함수는 seed를 이용해서 난수를 발생시키는데, 처음에 srand 함수로 특정한 값으로 초기화 된다. 

 

일정 범위 내의 난수를 발생시키기 위해서는 modulo 연산을 주로 사용한다. 

v1 = rand() * 100 // 0~99 까지의 난수 발생

v2 = rand() %100 + 1; // 1~100까지의 난수 발생

v3 = rand() % 30 + 1985 : 1985 ~2014 까지의 난수 발생

 

하지만 modulo 연산을 통해 특정 범위의 난수를 발생시키면 완전히 분산된 난수를 발생시키지는 못한다. 

 

c++ 사용 설명서에 나오는 예시를 보면

/* rand example: guess the number */
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  int iSecret, iGuess;

  /* initialize random seed: */
  srand (time(NULL));

  /* generate secret number between 1 and 10: */
  iSecret = rand() % 10 + 1;

  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&iGuess);
    if (iSecret<iGuess) puts ("The secret number is lower");
    else if (iSecret>iGuess) puts ("The secret number is higher");
  } while (iSecret!=iGuess);

  puts ("Congratulations!");
  return 0;
}

현재 시간을 시드로 사용해서 난수를 발생시키는 예시가 나온다. 

 

참고: https://www.cplusplus.com/reference/cstdlib/rand/

 

rand - C++ Reference

123 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

www.cplusplus.com

 

'언어 > C&C++ 응용' 카테고리의 다른 글

[C] Visual Studio 경고 레벨 높이기  (0) 2021.08.11
[C] Visual Studio 간단 디버깅  (0) 2021.08.05
[C] LNK1168 에러  (0) 2021.08.03
[C] Visual Studio scanf 해결  (0) 2021.08.02
[C++] STL vector  (0) 2021.06.22