If you have two points a = [x1, y1]
, and b = [x2, y2]
, when entering the point c = [x1, y2]
, you will have a rectangle triangle with the right angle at the vertex c
. This triangle has as one of the catetos, the side ac
, measuring |y2-y1|
. The other cateto is the side bc
, measuring |x2-x1|
. Calculating the size of these two headings is easy because they are aligned relative to one of the axes (one on x and the other on y), and therefore their length is the difference of the positions relative to the other axis.
With this, the distance between the points a
and b
can be calculated with Pythagoras' theorem because the ab
is the hypotenuse of this right triangle.
Here’s what your code looks like:
#include <iostream>
#include <cmath>
using namespace std;
class Ponto {
public:
Ponto(int x1, int y1) : x(x1), y(y1) {}
double calcular_distancia(Ponto &outro) {
int a = x - outro.x;
int b = y - outro.y;
return sqrt(a * a + b * b);
}
int inline get_x() {
return x;
}
int inline get_y() {
return y;
}
private:
int x;
int y;
};
int main() {
Ponto p1(2, -3);
Ponto p2(4, 5);
double distancia = p1.calcular_distancia(p2);
cout << distancia;
}
See here working on ideone.