C함수 난수 seed 지정 srand()
난수를 생성하기 위해서 난수의 생성 초기값인 난수 seed값을 지정합니다.
- 헤더: stdlib.h
- 형태: void srand( unsigned int seed)
- 인수: unsigned int seed 난수 seed
- 반환: -
rand() 함수만 사용하면 프로그램을 새로 실행할 때 마다 매번 다른 난수를 만들어 내지 않고 같은 난수를 반복하게 됩니다.
#include <stdio.h>
#include <stdlib.h>
int main( void)
{
int ndx;
for ( ndx = 0; ndx < 10; ndx++) {
printf( "%d %dn", ndx, rand() % 100);
}
return 0;
}
결과를 보듯이 난수는 생성하지만 실행할 때마다 똑 같은 난수를 똑 같이 생성합니다. 이 문제를 해결하기 위해서는 난수를 생성하기 전에 난수를 생성하기 위한 씨앗 즉, 난수 seed를 srand()로 바꾸어 주어야 합니다.
C언어 srand() 함수 예제
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // time()
#include <unistd.h> // getpid()
int main( void)
{
int ndx;
srand( (unsigned)time(NULL)+(unsigned)getpid());
for ( ndx = 0; ndx < 5; ndx++)
printf( "%d %d\n", ndx, rand() %100 +1);
return 0;
}
C언어 srand() 예제 실행 결과
]$ ./a.out
0 45
1 48
2 72
3 60
4 78
]$ ./a.out
0 2
1 80
2 63
3 99
4 93
]$
'컴퓨터 > 프로그래밍' 카테고리의 다른 글
C언어 제곱 계산 함수 pow() (0) | 2020.03.13 |
---|---|
C언어 난수 함수 rand() (0) | 2020.03.13 |
C언어 double형 값에서 정수부와 소수부 구하기 함수 modf() (0) | 2020.03.13 |