1. 라이브러리 함수
라이브러리 함수란 컴파일러에서 제공하는 함수이다.
거의 필수적으로 사용하는 <stdio.h>의 표준입출력함수도 라이브러리 함수이다.
-math.h
여러 수학 계산을 지원하는 라이브러리이다.
다음과 같은 기능들을 지원한다.
ex) 올림(ceil)함수와 내림(floor)함수
#include <stdio.h>
#include <math.h>
int main(){
double value = 1.6; double result;
result = floor(value); //내림
printf("%lf\n",result);
result = ceil(value); //올림
printf("%lf",result);
return 0;
}
>>>
1.0
2.0
2. 난수 생성
-rand() 함수
라이브러리 stdlib.h의 int rand(void);는 0부터 RAND_MAX(32767)까지의 난수를 생성하는 함수이다.
(2byte할당)
seed에 따라서 사실 나오는 값이 정해져 있다.
예를 들어, 시드가 기본값인 1일 때 (seed = 1), 47 18467 6334 26500 19169...로 정해진 결과가 출력될 것이다.
#include <stdio.h>
#include <stdlib.h>
int main(){
int i;
for (i=0;i<5;i++) printf("%d ",rand());
return 0;
}
-srand() 함수
앞의 예시와 같이, seed값이 바뀌지 않는다면 난수가 난수로서의 역할을 할 수가 없다.
따라서 seed값을 변경해주어야 하는데, 이때 쓰이는 함수가 void srand(unsigned int seed) ; 함수이다.
es) srand(2000); //seed값을 2000으로 변경해 준다.
#include <stdio.h>
#include <stdlib.h>
int main(){
srand(2000);
int i;
for (i=0;i<5;i++) printf("%d ",rand());
return 0;
}
마찬가지로, seed값을 변경해 주어도 결국 변경한 시드에서 다시 같은 값만 반복해서 나올 것이다.
이를 보완해 주기 위해 seed값이 시시각각 변할 필요가 있다.
-time()함수
time.h 라이브러리의 time()함수는 시각값을 불러와주는 함수이다.
시각은 매 순간 변하기 때문에 seed값을 시각값(time(NULL), time(0)) 혹은 시각을 이용하는 어떤 변수로 설정해주면 매 순간 계속 다른 난수가 생성될 것이다.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand((unsigned) time(NULL) * (unsigned) time(NULL));
int i;
for (i=0;i<5;i++) printf("%d ",rand());
return 0;
}
'CS > C언어' 카테고리의 다른 글
[C언어] 6. 반복문(2) - 중첩반복문, break, continue (0) | 2024.06.06 |
---|---|
[C언어] 6. 반복문(1) -while문, for문 (0) | 2024.06.06 |
[C언어] 5. 선택문(1) - if문 (1) | 2024.06.05 |
[C언어] 4(2) - 연산자(2) - 비트연산자, 연산자 우선순위 (0) | 2024.06.05 |
[C언어] 4. 연산자(1) - 산술, 대입, 복합대입, 증감, 관계/논리, 조건 (0) | 2024.06.04 |