윤성우의 열혈 C 프로그래밍 - 다양한 형태의 구조체 정의 [23-2]

Yumin Jung·2023년 10월 11일
0

방법 1

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

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

int Rectangle(Point po1, Point po2) {
	int res;
	res = (po1.xpos - po2.xpos) * (po1.ypos - po2.ypos);
	return res;
}

void Infor(Point po1, Point po2) {
	printf("좌 상단: [%d,%d]\n", po1.xpos, po2.ypos);
	printf("좌 하단: [%d,%d]\n", po1.xpos, po1.ypos);
	printf("우 상단: [%d,%d]\n", po2.xpos, po2.ypos);
	printf("우 하단: [%d,%d]\n", po2.xpos, po1.ypos);
}
int main(void) {
	Point cal1 = { 0,0 };
	Point cal2 = { 100,100 };
	printf("사각형의 크기는 : %d\n\n", Rectangle(cal1, cal2));
	Infor(cal1, cal2);
	return 0;
}

직사각형의 넓이를 구하기 위해서 구조체 변수를 선언하여 크기와 좌표정보를 나타냈다. 하지만, 2개 이상의 사각형 크기와 정보를 나타낼때는 아래와 같이 코드를 작성해야한다.

방법 2(해설 참고했음)

구조체변수를 포함하는 구조체변수를 만들었다.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

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

typedef struct rectangle{
	Point ul; //좌 상단
	Point lr; //우 하단
}Rectangle;'

void ShowRecArea(Rectangle rec) {
	printf("넓이 : %d\n", (rec.lr.xpos - rec.ul.xpos) * (rec.lr.ypos - rec.ul.ypos));
}

void ShowRecPos(Rectangle rec) {
	printf("좌 상단: [%d,%d]\n", rec.ul.xpos, rec.ul.ypos);
	printf("좌 하단: [%d,%d]\n", rec.ul.xpos, rec.lr.ypos);
	printf("우 상단: [%d,%d]\n", rec.lr.xpos, rec.ul.ypos);
	printf("우 하단: [%d,%d]\n", rec.lr.xpos, rec.lr.ypos);
}

int main(void) {
	Rectangle rec1 = { {1,1},{4,4} };
	Rectangle rec2 = { {0,0},{7,5} };
	ShowRecArea(rec1);
	ShowRecPos(rec1);
	ShowRecArea(rec2);
	ShowRecPos(rec2);
	return 0;
}
profile
문과를 정말로 존중해

0개의 댓글