C 언어에서 rand와 srand를 활용한 난수 생성
C 언어에서 난수를 생성하는 방법 중 가장 기본적인 함수는 rand()
입니다. 그러나 rand()
함수는 항상 동일한 시퀀스의 난수를 생성하기 때문에, 이를 방지하기 위해 srand()
를 사용하여 초기 시드를 설정해야 합니다.
본 포스팅에서는 rand
와 srand
의 기본적인 사용법과 다양한 예제를 통해 난수 생성 방법을 설명하겠습니다.
1. rand() 함수 개요
rand()
함수는 stdlib.h
헤더 파일에 정의되어 있으며, 호출할 때마다 0에서 RAND_MAX
(보통 32767) 사이의 정수를 반환합니다.
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("난수 1: %d\n", rand());
printf("난수 2: %d\n", rand());
printf("난수 3: %d\n", rand());
return 0;
}
위 코드를 실행하면 매번 동일한 값이 출력됩니다. 이는 rand()
가 내부적으로 같은 초기 상태에서 실행되기 때문입니다.
2. srand()를 이용한 시드 설정
rand()
의 결과를 변경하려면 srand()
를 사용하여 시드를 초기화해야 합니다. 보통 현재 시간을 활용하여 시드를 설정합니다.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // 현재 시간을 기반으로 시드 설정
printf("난수 1: %d\n", rand());
printf("난수 2: %d\n", rand());
printf("난수 3: %d\n", rand());
return 0;
}
위 코드에서는 time(NULL)
을 사용하여 현재 시간을 시드로 설정하므로, 실행할 때마다 다른 난수를 얻을 수 있습니다.
3. 특정 범위의 난수 생성
rand()
가 생성하는 값은 0부터 RAND_MAX
까지이므로, 원하는 범위의 난수를 얻으려면 적절한 변환이 필요합니다.
3.1. 1부터 100 사이의 난수 생성
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
for (int i = 0; i < 5; i++) {
int random_num = (rand() % 100) + 1; // 1~100 범위
printf("%d\n", random_num);
}
return 0;
}
3.2. 특정 범위 [min, max]의 난수 생성
int getRandom(int min, int max) {
return (rand() % (max - min + 1)) + min;
}
int main() {
srand(time(NULL));
for (int i = 0; i < 5; i++) {
printf("%d\n", getRandom(10, 50)); // 10~50 범위
}
return 0;
}
4. 난수를 활용한 예제
4.1. 주사위 굴리기
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
printf("주사위 결과: %d\n", (rand() % 6) + 1);
return 0;
}
4.2. 동전 던지기 (앞면/뒷면 결정)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
if (rand() % 2 == 0) {
printf("앞면\n");
} else {
printf("뒷면\n");
}
return 0;
}
4.3. 배열에서 랜덤한 값 선택
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
const char *items[] = {"사과", "바나나", "포도", "오렌지", "체리"};
int size = sizeof(items) / sizeof(items[0]);
srand(time(NULL));
printf("선택된 과일: %s\n", items[rand() % size]);
return 0;
}
5. 난수의 품질 개선
C 표준 라이브러리의 rand()
는 비교적 단순한 난수 생성기이므로, 암호학적 보안이 필요한 경우에는 random()
, arc4random()
, 또는 mt19937
(Mersenne Twister)를 사용하는 것이 좋습니다.
5.1. Mersenne Twister를 활용한 난수 생성 (C++ 사용)
#include <iostream>
#include <random>
#include <ctime>
int main() {
std::mt19937 mt(time(NULL));
std::uniform_int_distribution<int> dist(1, 100);
for (int i = 0; i < 5; i++) {
std::cout << dist(mt) << std::endl;
}
return 0;
}
6. 마무리
본 포스팅에서는 rand()
와 srand()
를 사용하여 난수를 생성하는 방법을 살펴보았습니다. 기본적인 사용법부터 특정 범위의 난수 생성, 실전 예제, 그리고 난수 생성 품질을 개선하는 방법까지 다루었습니다.
rand()
는 기본적인 난수 생성에는 유용하지만, 보안이 필요한 경우 더 강력한 난수 생성기를 사용하는 것이 좋습니다. 프로그램에서 난수를 효과적으로 활용하기 위해 적절한 시드 설정과 범위 조정을 고려해야 합니다.
'c 언어 > c 표준 라이브러리(Standard C Library)' 카테고리의 다른 글
C 표준 라이브러리 `ctype.h` 개요 및 문자 판별 함수 (0) | 2025.03.01 |
---|---|
C qsort와 bsearch를 활용한 정렬 및 검색 (0) | 2025.02.28 |
C 표준 API 프로그램 종료 및 반환값 (atexit, quick_exit) (0) | 2025.02.26 |
C 표준 API: 시스템 호출 및 종료 (system, exit, abort) (0) | 2025.02.25 |
C 언어에서 환경 변수 다루기 (getenv, putenv, setenv, unsetenv) (0) | 2025.02.24 |