IT

c언어 랜덤숫자(rand()함수)

배채 2025. 1. 6. 11:50
#include <stdio.h>
#include<time.h>
#include<stdlib.h>
int main(void) {
    srand((unsigned)time(NULL));
    printf("%d", rand());
    return 0;

코드 설명:

  1. 헤더 파일 포함:stdio.h는 표준 입출력 함수를 사용하기 위한 헤더 파일입니다. time.h는 시간 관련 함수를 사용하기 위한 헤더 파일이고, stdlib.h는 난수 생성 함수와 일반 유틸리티 함수를 사용하기 위한 헤더 파일입니다.
  2. c
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    
  3. main 함수 정의:main 함수는 프로그램의 진입점입니다.
    int main(void) {
    
  4. 난수 초기화:srand 함수는 난수 생성기의 초기값(seed)을 설정합니다. 여기서는 현재 시간을 time(NULL) 함수로 받아와서 이를 초기값으로 사용합니다. 이를 통해 매번 다른 난수를 생성할 수 있습니다. (unsigned)는 time(NULL) 함수의 반환 값을 unsigned int 타입으로 변환합니다.
    srand((unsigned)time(NULL));
    
  5. 난수 출력: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;

}

반응형