윤성우 열혈 C++프로그래밍 연습 2- 4[C++의 표준함수 호출]
: rand, srand, time을 이용해서 0이상 100미만의 난수를 총 5개 생성하는 예제
1) rand 함수
- headerfile : stdlib.h / csdlib
- prototype : int rand(void)
0 부터 RAND_MAX까지 범위 내 랜덤한 숫자를 반환함
but rand()함수는 프로그램이 생성 시 값이 정해지기 때분에 프로그램을 이후에 실행햐여도 동일한 결과값도출
-> rand함수는 srand함수랑 함께 사용
2) srand 함수
- headerfile : stdlib.h / csdlib
- prototype : void srand (unsigned int seed)
seed 값에 따라 rand의 값이 변화함( rand함수만 호출한 경우, srand(1) 호출 후 rand함수 호출과 동일함)
-> 결과적으로 seed값이 계속 바뀌어야 동일한 난수가 나오지 않음
3) time 함수
- headerfile : time.h / ctime
- prototype : time_t time (time_t *tloc)
1970년 1월 1일 0시(UTC)부터 현재까지 흐른 시간을 sec 단위로 반환
-> seed값에 time함수를 이용해 지금의 시간을 반환하면 seed의 값은 계속해서 변화함
-
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(void)
{
srand((unsigned int)time(NULL)); 함수의 형태에 맞게 time함수 반환값을 unsigned int형으로 형변환함
int num = 0;
for (int i = 0; i < 5 ; i++) 난수 5개 형성
{
num = rand(); 난수형성
cout << num % 100 << endl; 난수를 100으로 나누어 난수의 범위는 0부터 99까지
}
return 0;
}