728x90
반응형
난수(Random number) : 규칙성 없이 임의로 생성되는 수
#include <stdlib.h>
#include <time.h>
↑난수를 발생시키기 위해서는 위 두개의 헤더파일을 포함시켜주어야 한다.
1. 난수 발생
① #include <stdlib.h> 선언
② rand(); 0 ~ 32767(rand_max)
ex) for(int i = 0; i < 5; i++)
{
printf("%d\n", rand());
}
--> 매번 같은 숫자 5개 출력
2. seed값(초기값) 설정
ㄴ 매번 실행값이 다른 난수를 발생시킴
① #include <time.h> 선언
② srand(초기값)
srand((unsigned)time(NULL)); // 명시적 형변환(캐스팅)
ex) for(int i = 0; i < 5; i++)
{
printf("%d\n", rand());
}
--> 매번 다른 숫자 5개 출력
3. 난수 범위 설정
1 + rand() % 100 // 1~100까지, 1부터 범위를 줄 때는 1 + rand() % max
rand() % 101 // 0~100까지, 0부터 범위를 줄 때는 rand() % (n+1)
4. 유틸리티 함수
ㄴ 윈도우에서만 사용가능
exit(int status) -> exit()를 호출하면 호출 프로세스를 종료시킴
int system(const char *command)?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
system("dir");
printf("아무 키나 입력하세요");
_getch();
system("cls");
return 0;
}
5. 수학 라이브러리 함수
ㅇ abs(int x) // fabs(double x)
- 절댓값
ㅇ pow(double x, double y)
- x^y
ㅇ sprt(double x)
- 제곱근
ㅇ cell(double x)
- x보다 큰 가장 작은 정수를 반환
ㅇ floor(double x)
- x보다 작은 가장 큰 정수를 반환
//랜덤 난수 출력하기
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
int main(void)
{
srand((unsigned)time(NULL));
for (int i = 1; i <= 10; i++)
{
int rands = 0;
for (int j = 1; j <= 1; j++)
{
rands = rand() % 2;
printf("%d ", rands);
}
}
return 0;
}
//동전 앞면, 뒷면 맞추기
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
int coinch(void);
int main(void)
{
while (1)
{
int choose;
printf("앞면 또는 뒷면(1 또는 0): \n");
scanf("%d", &choose);
if (choose != 1 && choose != 0)
{
printf("다시 입력하시오\n");
continue;
}
int ch = coinch();
if (ch == choose)
{
printf("맞았습니다!\n");
}
else
{
printf("틀렸습니다!\n");
}
printf("계속하시겠습니까? (y 또는 n)\n");
char gos;
scanf(" %c", &gos);
if (gos == 'y')
continue;
else if (gos == 'n')
break;
else
printf("다시 입력하시오\n");
}
return 0;
}
int coinch(void)
{
int coin = 0;
srand((unsigned)time(NULL));
while(1)
{
coin = 0+rand() % 2;
break;
}
return coin;
}
//랜덤 실수 출력하기
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
int main(void)
{
double rn = 0;
srand((unsigned)time(NULL));
for (int i = 1; i <= 5; i++)
{
rn = rand() / (double)RAND_MAX;
printf("%f ", rn);
}
return 0;
}
//자동차 경주 게임 만들기
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
void disp_car(int car_num, int dis)
{
printf("CAR #%d\n", car_num);
for (int i = 1; i <= dis / 10; i++)
{
printf("*");
}
printf("\n");
}
int main(void)
{
int dis_time;
printf("주행시간을 입력하시오");
scanf_s("%d", &dis_time);
//seed값 설정
srand((unsigned)time(NULL));
//주행거리 누적 변수 초기화
int car1_dist = 0, car2_dist = 0;
for (int i = 0; i < dis_time; i++)
{
//주행거리 누적
car1_dist += rand() % 100;
car2_dist += rand() % 100;
disp_car(1, car1_dist);
disp_car(2, car2_dist);
printf("--------------------\n");
_getch();
}
return 0;
}
728x90
반응형