본문 바로가기

스터디/코딩

[ 코딩 도장 : C ] Unit 50. 구조체 사용하기 : 연습문제 / 심사문제

50.2 연습문제 : 사각형의 넓이 구하기

문제) 다음 소스 코드를 완성하여 사각형의 넓이가 출력되게 만드세요.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>

struct Rectangle {
    int x1, y1;
    int x2, y2;
};

int main()
{
    struct Rectangle rect;
    int area;

    rect.x1 = 20;
    rect.y1 = 20;
    rect.x2 = 40;
    rect.y2 = 30;

    int width = abs(rect.x2 - rect.x1);
    int height = abs(rect.y2 - rect.y1);
    area = width * height;

    printf("%d\n", area);

    return 0;
}

 

 

50.3 심사문제 : 두 점 사이의 거리 구하기

문제) 표준 입력으로 정수 4개가 입력되어 Point2D 구조체에 저장됩니다. 다음 소스 코드를 완성하여 두 점 사이의 거리가 출력되게 만드세요.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>

struct Point2D {
    int x;
    int y;
};

int main()
{
    struct Point2D p1;
    struct Point2D p2;
    double distance;

    scanf("%d %d %d %d", &p1.x, &p1.y, &p2.x, &p2.y);

    int a = p2.x - p1.x;
    int b = p2.y - p1.y;
    distance = sqrt(a * a + b * b);

    printf("%f\n", distance);

    return 0;
}