Minwoo Dev.

<윤성우의 열혈 C프로그래밍> :: 23. 구조체와 사용자 정의 자료형 2 문제풀이 본문

C++

<윤성우의 열혈 C프로그래밍> :: 23. 구조체와 사용자 정의 자료형 2 문제풀이

itisminu 2023. 9. 10. 22:22
728x90
반응형
SMALL

문제 23-1 [구조체 변수의 연산]

다음 구조체의 두 변수를 대상으로 저장된 값을 서로 바꿔주는 함수를 정의하고 이를 호출하는 예제를 작성해 보자.

typedef struct point
{
    int xpos;
    int ypos;
} Point;

예를 들어서 다음과 같이 두 개의 구조체 변수가 선언된 상태에서,

Point pos1 = {2,4};
Point pos2 = {5,7};

이 두 구조체 변수를 대상으로, 혹은 두 구조체 변수의 주소 값을 대상으로 SwapPoint 라는 이름의 함수를 호출하면 pos1의 xpos, ypos에는 각각 5와 7이, 그리고 pos2의 xpos, ypos에는 각각 2와 4가 저장되어야 한다.

 

정답

#include<stdio.h>

typedef struct point
{
    int xpos;
    int ypos;
} Point;

void SwapPoint(Point * pos1, Point * pos2)
{
    Point temp;
    temp.xpos = pos1->xpos;
    pos1->xpos = pos2->xpos;
    pos2->xpos = temp.xpos;

    temp.ypos = pos1->ypos;
    pos1->ypos = pos2->ypos;
    pos2->ypos = temp.ypos;
}

int main(void)
{
    Point pos1 = {2,4};
    Point pos2 = {5,7};

    SwapPoint(&pos1,&pos2);

    printf("pos1 : [%d, %d]\n",pos1.xpos,pos1.ypos);
    printf("pos2 : [%d, %d]\n",pos2.xpos,pos2.ypos);

    return 0;
}

 

 

문제 23-2 [다양한 형태의 구조체 정의]

좌 상단의 x, y 좌표가 [0,0], 우 하단의 x, y 좌표가 [100,100] 인 좌표평면상의 직사각형 정보를 표현하기 위한 구조체 Rectangle 을 정의하되, 다음 구조체를 기반으로 정의해보자.

typedef struct point 
{
    int xpos;
    int ypos;
} Point;

 

그리고 Rectangle 구조체 변수를 인자로 전달받아서 해당 직사각형의 넓이를 계산해서 출력하는 함수와 직사각형을 이루는 네 점의 좌표정보를 출력하는 함수를 각각 정의해보자. 단, 좌표평면상에서 직사각형을 표현하기 위해서 필요한 점의 갯수는 4개가 아닌 2개이니, 직사각형을 의미하는 Rectangle 변수 내에는 두 점의 정보마나 존재해야 한다.

#include<stdio.h>

typedef struct point
{
    int xpos;
    int ypos;
} Point;

typedef struct rectangle
{
    Point p1;
    Point p2;
} Rectangle;

int RectangleArea(Rectangle rec)
{
    int area = (rec.p1.xpos - rec.p2.xpos) * (rec.p1.ypos - rec.p2.ypos);
    return area;
}

void ShowRectanglePos(Rectangle rec)
{
    printf("좌측 상단 : [%d, %d]\n",rec.p1.xpos,rec.p1.ypos);
    printf("좌측 하단 : [%d, %d]\n",rec.p1.xpos,rec.p2.ypos);
    printf("우측 상단 : [%d, %d]\n",rec.p2.xpos,rec.p1.ypos);
    printf("우측 하단 : [%d, %d]\n",rec.p2.xpos,rec.p2.ypos);
}

int main(void)
{
    Rectangle rec1 = {{0,0},{100,100}};
    Rectangle rec2 = {{2,4},{8,6}};
    RectangleArea(rec1);
    ShowRectanglePos(rec1);
    printf("\n");
    RectangleArea(rec2);
    ShowRectanglePos(rec2);
    
    return 0;
}

 

728x90
반응형
LIST