설명

난수를 생성합니다. rand()는 0부터 RAND_MAX 사이의 난수를 생성합니다. 그러나 문제는 프로그램을 새로 실행할 때 마다 매번 다른 난수를 만들어 내지 않고 계속 같은 난수를 반복하게 됩니다.

#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를 바꾸어 주어야 하며, seed를 바꾸기 위해서는 srand()를 사용해야 합니다. 이에 대한 자세한 설명은 강좌 게시판의 "난수 만들기"를 참고하여 주십시오.

헤더stdlib.h
형태int rand( void);
반환

int

0부터 RAND_MAX 사이의 난수
예제
#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 %dn", ndx, rand() %100 +1);

   return 0;
}

]$ ./a.out 0 45 1 48 2 72 3 60 4 78 ]$ ./a.out 0 2 1 80 2 63 3 99 4 93



+ Recent posts