Structures and Functions
Coddy의 C/C++ 구조체 코스 레슨 — 8개 중 5번째.
C/C++ 파일에서 구조체를 생성하면, 이 구조체를 함수의 인자나 반환 값 타입으로 사용할 수 있습니다.
예를 들어, Person이 구조체라고 가정해 봅시다:
void greet(Person p) {
cout << "Hello, " << p.name << endl;
}C에서는 앞에 struct 키워드를 추가해야 합니다:
void greet(struct Person p) {
printf("Hello, %s\n", p.name);
}챌린지
쉬움Point 구조체를 생성하고, 두 점을 초기화하며, 그 사이의 거리를 계산하는 코드의 일부가 주어집니다.
여러분의 작업은 두 개의 Point 구조체를 인자로 받아 거리를 계산하고 이를 반환(int 타입)하는 calcDistance라는 이름의 함수를 작성하는 것입니다.
두 점 p1과 p2가 주어졌을 때, 그 사이의 거리는 다음과 같습니다:
(p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)main 함수를 전혀 수정할 필요가 없습니다!
직접 해보기
#include <stdio.h>
struct Point {
int x;
int y;
};
// 여기에 calcDistance를 구현하세요
int main() {
char tmp[50];
int p1x, p1y, p2x, p2y;
scanf("%s %d %d", &tmp, &p1x, &p1y);
scanf("%s %d %d", &tmp, &p2x, &p2y);
struct Point p1 = {p1x, p1y};
struct Point p2 = {p2x, p2y};
int distance = calcDistance(p1, p2);
printf("Distance between p1 and p2: %d", distance);
return 0;
};