본문으로 바로가기
homeimage
  1. Home
  2. 컴퓨터/프로그래밍
  3. C언어 난수 함수 rand()

C언어 난수 함수 rand()

· 댓글개 · 바다야크

C함수 난수 만들기 rand()

난수를 생성합니다. rand()는 0부터 RAND_MAX 사이의 난수를 생성합니다.

  • 헤더: stdlib.h
  • 형태: int rand( void)
  • 인수: -
  • 반환: int 0부터 RAND_MAX 사이의 난수

rand() 함수만 사용하면 프로그램을 새로 실행할 때 마다 매번 다른 난수를 만들어 내지 않고 같은 난수를 반복하게 됩니다.

#include <stdio.h>
#include <stdlib.h>

int main( void)
{ 
   int   ndx;   
        
   for ( ndx = 0; ndx < 10; ndx++) {
      printf( "%d %dn", ndx, rand() % 100);
   }        
   return 0;
}

프로그램을 여러 번 실행해 봅니다.

]$ ./a.out
0 83
1 86
2 77
3 15
4 93
]$ ./a.out
0 83
1 86
2 77
3 15
4 93
]$

결과를 보듯이 난수는 생성하지만 실행할 때마다 똑 같은 난수를 똑 같이 생성합니다. 이 문제를 해결하기 위해서는 난수를 생성하기 전에 난수를 생성하기 위한 씨앗 즉, 난수 seed를 srand()로 바꾸어 주어야 합니다.

C언어 rand() 함수 예제

#include <stdio.h>
#include <stdlib.h>
#include <time.h>    // time()
#include <unistd.h>  // getpid()
int main( void)
{
   int   ndx;

   srand( (unsigned)time(NULL)+(unsigned)getpid());
   for ( ndx = 0; ndx < 5; ndx++)
      printf( "%d %d\n", ndx, rand() %100 +1);

   return 0;
}

C언어 rand() 예제 실행 결과

]$ ./a.out
0 45
1 48
2 72
3 60
4 78
]$ ./a.out
0 2
1 80
2 63
3 99
4 93
]$
SNS 공유하기
💬 댓글 개
이모티콘창 닫기
울음
안녕
감사해요
당황
피폐

이모티콘을 클릭하면 댓글창에 입력됩니다.