Creative Code

main.c(rand함수) 본문

C Programming

main.c(rand함수)

빛하루 2023. 8. 4. 10:58

※main.c 파일

#include <stdio.h>
#include <time.h>  // user의 헤더파일을 가져올 때
#include "rand.h" // 같은 디렉토리 안에 있는 헤더파일을 가져올 때

int main(void)
{
	my_srand(time(NULL)); 
	
	for (int i = 1; i<=10; i++) {
		int num = my_rand();
		printf("%d\n",num);
	}
	return 0;
}

※rand.h파일

//#Pragma ONCE헤더파일을 한번만 include 한다는 뜻 
#ifndef RAND_H
#define RAND_H

void my_srand(int); // function declaration 함수 선언
int my_rand(void);

#endif

 

※rand.c파일

static int seed; // 같은 .c파일 안에 있는 함수들만 접근가능
					// -> my_stand함수와 my_rand함수만 접근이 가능하다.
					// -> 허용된 연산을 통해서만 데이터에 접근하게 할 때 사용(직접적으로 접근x)
void my_srand(int s) // function definition
{
	seed = s;
}

int my_rand(void) 
{
	seed = 1103515245 * seed +12345;
	return ((unsigned)(seed/65536)%32768);
}

 

'C Programming' 카테고리의 다른 글

main.c(구조체)  (0) 2023.08.04
main.c(serial함수)  (0) 2023.08.04
main.c(함수 선언)  (0) 2023.08.04
main.c (랜덤함수 라이브러리 생성)  (0) 2023.08.04
swap3.c(전역변수 사용)  (0) 2023.08.04