본문 바로가기

반응형

C

(149)
[C언어] 공용체 (Union) 공용체(Union)는 새로운 자료형을 선언한 뒤 해당 자료형에 멤버를 담아 사용하며, 보유한 멤버들 중 크기가 가장 큰 변수의 메모리 공간을 공유한다. #include struct student1{ // 구조체 선언 int id; double score; }; union student2{ // 공용체 선언 int id; double score; }; int main(){ struct student1 str_stu = {123, 89.5}; union student2 uni_stu = {456}; printf("구조체 크기 : %d, 유니온 크기 : %d\n\n", sizeof(str_stu), sizeof(uni_stu)); printf("구조체 id 주소 : %p, score 주소 : %p\n", &s..
[C언어] 실습: 헤더 파일 및 C 파일 만들기 헤더 파일 및 C 파일 만들기 1. main.c #include #include"point.h" #include"line.h" #include"rect.h" double distance(Line *pLine); double area(Rect *pRect); int main(){ Line l1 = {{10, 40}, {30, 20}}; Rect r1 = {{10, 40}, {30, 20}}; printf("point1 (%d, %d), point2 (%d, %d)\n", l1.start.x, l1.start.y, l1.end.x, l1.end.y); printf("직선의 길이 : %.2lf\n\n", distance(&l1)); printf("point1 (%d, %d), point2 (%d, %d)\n"..
[C언어] 실습: 배열에 저장된 정수의 합 출력하기 배열에 저장된 정수의 합 출력하기 #include void add(int *arr, int *sum); int main(){ int arr[5] = {1, 2, 3, 4, 5}; int sum = 0; add(arr, &sum); // arr[]는 배열이기 때문에 첫번째 element의 주소값을 가지고 있다. printf("합 : %d\n", sum); return 0; } void add(int *arr, int *sum){ for(int i = 0; i < 5; ++i){ *sum += arr[i]; } }
[C언어] time(NULL) time() 함수는 #include 헤더 파일에서 사용할 수 있다. time(NULL) 함수는 1970년 1월 1일 0시 0분 0초를 기점으로 현재 시간까지의 시간을 계산해 준다. (초 단위) #include time(NULL);
[C언어] 난수 생성 함수 난수는 특정한 의미를 지니고 있지 않는 임의의 숫자이다. 1. rand() #include 헤더 파일로 불러올 수 있으며, 난수를 생성할 때 사용한다. #include rand() // 난수 생성 함수 rand() % (b - a + 1); // a~b까지의 난수 생성 2. srand() #inlude 헤더 파일로 불러올 수 있으며, 시드 값을 변경하는 함수이다. #include srand(unsigned int); srand() 함수의 인자에 따라 rand() 함수를 이용해 생성한 난수 값이 변경된다. 즉 srand()의 인자가 a라면, rand() 함수로 생성한 난수는 b만 나온다.
[C언어] 실습: rand() 함수를 이용하여 x, y 좌표값 출력하기 rand() 함수를 이용하여 x, y 좌표값 출력하기 #include #include #include // rand() #include // time() typedef struct point{ int x; int y; } Point; void set_point(Point *pArr, int x, int y); void print_point(const Point *pArr); int main(){ Point arr[5] = {0}; // Point 구조체의 변수 arr[]를 선언하고, index를 모두 0으로 초기화 해준다. int size = sizeof(arr) / sizeof(arr[0]); // 구조체 변수 arr[]에서 하나의 index 크기는 int x와 int y때문에 8byte이다. sran..
[C언어] 실습: 신입사원의 이름, 학점, 토익점수를 입력하여 엘리트 사원 데이터 출력하기 신입사원의 이름, 학점, 토익점수를 입력하여 엘리트 사원 데이터 출력하기 1. 신입사원의 수는 5명으로 하고, 구조체 배열을 선언한다. 2. 구조체 배열의 데이터는 키보드를 통해 입력받는다. 3. 엘리트 사원의 조건은 학점 4.0 이상, 토익점수 900점 이상인 사원을 의미한다. 4. 기타 조건은 일반적인 프로그램의 흐름에 맞게 구현한다. #include typedef struct profile{ char name[10]; double grade; int toeic; } Profile; int main(){ Profile new[5]; for(int i = 0; i < 5; ++i){ printf("[%d 신입사원 정보]\n", i + 1); printf("이름 : "); scanf("%s", &new[..
[C언어] 실습: 입력받은 문자열을 저장하고, 출력하는 프로그램 구현하기 입력받은 문자열을 저장하고, 출력하는 프로그램 구현하기 #include #include // strlen(), strcpy() int main(){ char *str; char tmp[20]; printf("Input : "); scanf("%s", tmp); str = (char*)malloc(strlen(tmp) + 1); // tmp에 입력된 문자열의 길이('\0' 이전까지의 문자열 길이)에 +1을 한 크기로 정해준다. strcpy(str, tmp); printf("Output : %s\n", str); free(str); // 동적할당을 해제해준다. return 0; }

반응형