time(시간) rand(난수) srand(난수 씨드) C 함수 레퍼런스

|
                        

time

원형 time_t time(time_t *timer); 

헤더파일 time.h

1970년 1월 1일 이후 경과한 초를 리턴한다.


#include <stdio.h>

#include <time.h>


void main()

{

time_t t;

time(&t);

printf("time : %ld\n",t);

}



rand

원형 int rand(void);

헤더파일 stdlib.h

무작위 난수를 만들어 리턴한다.


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

void main()
{
int i;
time_t t;
time(&t);
printf("time : %ld\n",t);

for(i=0;i<15;i++)
{
printf("%d : %d\n", i+1,rand());
}

}
프로그램이 다시 시작될 때 마다 반복된 난수가 나온다.



srand

원형 void srand(unsigned seed);

헤더파일 stdlib.h

seed가 다르면 다른 패턴의 난수가 생성된다.


#include <stdio.h>

#include <time.h>

#include <stdlib.h>


void main()

{

int i;

time_t t;

time(&t);

printf("time : %ld\n",t);


srand(100);  // 시드값 100일때

//srand(777);  // 시드값 777일때


for(i=0;i<15;i++)

{

printf("%d : %d\n", i+1,rand());

}


}





프로그램 실행중 실시간 난수를 생성하기

시간을 srand()에 넣어서 난수를 생성한다.


#include <stdio.h>

#include <time.h>

#include <stdlib.h>


void main()

{

int i;

time_t t;

time(&t);

printf("time : %ld\n",t);


srand(t);


for(i=0;i<15;i++)

{

printf("%d : %d\n", i+1,rand());

}


}





And