#include <stdio.h>
#include<time.h>
#include<stdlib.h>
int main(void) {
srand((unsigned)time(NULL));
printf("%d", rand());
return 0;
코드 설명:
- 헤더 파일 포함:stdio.h는 표준 입출력 함수를 사용하기 위한 헤더 파일입니다. time.h는 시간 관련 함수를 사용하기 위한 헤더 파일이고, stdlib.h는 난수 생성 함수와 일반 유틸리티 함수를 사용하기 위한 헤더 파일입니다.
-
c
#include <stdio.h> #include <time.h> #include <stdlib.h>
- main 함수 정의:main 함수는 프로그램의 진입점입니다.
int main(void) {
- 난수 초기화:srand 함수는 난수 생성기의 초기값(seed)을 설정합니다. 여기서는 현재 시간을 time(NULL) 함수로 받아와서 이를 초기값으로 사용합니다. 이를 통해 매번 다른 난수를 생성할 수 있습니다. (unsigned)는 time(NULL) 함수의 반환 값을 unsigned int 타입으로 변환합니다.
srand((unsigned)time(NULL));
- 난수 출력:rand 함수는 난수를 생성하여 반환합니다. 생성된 난수를 printf 함수를 사용하여 출력합니다.
printf("%d", rand());
로또번호 추첨
#include <stdio.h>
#include<time.h>
#include<stdlib.h>
int main(void) {
srand((unsigned)time(NULL));
for(int i=0;i<6;i++){
printf("%10d\n", rand()%45);
}
return 0;
}
반응형
'IT' 카테고리의 다른 글
기초컴퓨터프로그래밍 C언어(8)-함수 (0) | 2025.01.08 |
---|---|
기초컴퓨터프로그래밍 C언어(7)-중첩반복문、삼각형 별찍기 (0) | 2025.01.06 |
기초컴퓨터프로그래밍 C언어(6)-while, for 반복문 (0) | 2025.01.03 |
기초컴퓨터프로그래밍 C언어(5)-조건문 (3) | 2025.01.02 |
스마트그리드란? - 포스터 공모전(1) (1) | 2025.01.02 |