C함수 난수 만들기 rand()
난수를 생성합니다. rand()는 0부터 RAND_MAX 사이의 난수를 생성합니다.
- 헤더: stdlib.h
- 형태: int rand( void)
- 인수: -
- 반환: int 0부터 RAND_MAX 사이의 난수
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;
}
프로그램을 여러 번 실행해 봅니다.
]$ ./a.out
0 83
1 86
2 77
3 15
4 93
]$ ./a.out
0 83
1 86
2 77
3 15
4 93
]$
결과를 보듯이 난수는 생성하지만 실행할 때마다 똑 같은 난수를 똑 같이 생성합니다. 이 문제를 해결하기 위해서는 난수를 생성하기 전에 난수를 생성하기 위한 씨앗 즉, 난수 seed를 srand()로 바꾸어 주어야 합니다.
C언어 rand() 함수 예제
#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언어 rand() 예제 실행 결과
]$ ./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언어 난수 seed 지정 함수 srand() (0) | 2020.03.13 |
---|---|
C언어 double형 값에서 정수부와 소수부 구하기 함수 modf() (0) | 2020.03.13 |
C언어 소수점 이하 모두 버림 함수 floor() (0) | 2020.03.13 |