If you have two points a = [x1, y1]
, and b = [x2, y2]
, entering the c = [x1, y2]
point will give you a right triangle with the right angle at the c
vertex. This triangle has as one of the legs, the ac
side, which measures |y2-y1|
. The other side is the bc
side, which measures |x2-x1|
. Calculating the size of these two legs is easy because they are aligned in relation to one of the axes (one in x and the other in y), and therefore their length is the difference of positions relative to the other axis.
Thus, the distance between the points a
and b
can be calculated with the Pythagorean theorem, since the segment ab
is the hypotenuse of that triangle rectangle.
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.