How do I get data from an object and do a math operation with another object in C ++?

1

I have to calculate the distance between two points in C ++ (Object Oriented)

Here is the code I have:

Ponto p1(2,-3);
Ponto p2(4,5);

class Ponto
{
public:
    Ponto(int x1, int y1) : x(x1), y(y1) {}

    CalculaDist ();

private:
    int x;
    int y;
};

How to do this?

    
asked by anonymous 29.09.2017 / 20:42

3 answers

7

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.

    
29.09.2017 / 22:41
5

To calculate the distance between two points in a Cartesian plane the following formula applies:

Basedontheexampleofyourquestion,hereisapossiblesolutiontoyourproblem:

#include<iostream>#include<cmath>classPonto{public:Ponto(intx,inty):x(x),y(y){}virtual~Ponto(void){}doubleCalculaDist(constPonto&p){intx1=p.x-this->x;inty1=p.y-this->y;doubled=std::pow(x1,2)+std::pow(y1,2);returnstd::sqrt(d);}private:intx;inty;};intmain(void){Pontop1(2,-3);Pontop2(4,5);std::cout<<"Distancia: " << p1.CalculaDist( p2 ) << std::endl;

    return 0;
}

Output:

$ ./distancia
Distancia: 8.24621
    
29.09.2017 / 22:43
5

As I suspect that the concept of distance itself was not very clear, I will leave here my contribution, just as a complement to the already very good responses of @VictorStafusa and @Lacobus.

So I present a diagram that I elaborated on the calculation you are trying to make and their representations in the Cartesian plane.

Noticethatthecalculationfortheredline,thedistance,followsthePythagoreantheorem,as@VictorStafusaalreadyindicated.

Thisisformallypresentedas:

For example:

  • h - hypotenuse that corresponds to distance, red line
  • a - pipe that corresponds to the blue line
  • b - pipe that corresponds to the yellow line
29.09.2017 / 23:50