C_C++

(C/C++) 두 점 사이의 거리, point 구조체 이용

고니자니 2022. 11. 8. 16:28
반응형

두 점 사이의 거리 구하기

 

점(x1, y1)과 점(x2, y2)의 거리를 d라고 하면, 다음과 같이 두 점 사이의 거리를 구할 수 있습니다.

두 점 사이의 거리를 구하는 공식

 

 

다음 코드는 두 점 사이의 거리를 point 구조체를 이용해서 구하는 C언어 프로그래입니다.

#include <stdio.h>
#include <math.h>

struct point {
	int x, y;
};

double distance(struct point p1, struct point p2)
{
	return sqrt(pow((p2.x - p1.x), 2) + pow((p2.y - p1.y), 2));
}

int main()
{
	struct point p1 = { 10, 20 };
	struct point p2 = { 30, 40 };

	printf("거리: %f\n", distance(p1, p2));

	return 0;
}

 

p1(10, 20)

p2(30,40)

두 점 사이의 거리: 28.284271

 

 

반응형

 

C++ 코드

#include <iostream>
#include <cmath>
using namespace std;

struct point {
	int x, y;
};

double distance(struct point p1, struct point p2)
{
	return sqrt(pow((p2.x - p1.x), 2) + pow((p2.y - p1.y), 2));
}

int main()
{
	struct point p1 = { 10, 20 };
	struct point p2 = { 30, 40 };

	cout << "두 점 사이의 거리: " << distance(p1, p2) << endl;

	return 0;
}

 

두 점 사이의 거리

 

728x90
반응형