How to calculate Euclidean distance

6

I want to calculate the Euclidean distance using the following formula:

SoItried,makingthiscode:

#defineSLEEP_11000voidHeaderClass::DistanciaEuclidianaEntrePontos(){intx1,x2,y1,y2,distancia;std::cout<<"Coordenadas ponto 1 (x): ";
    std::cin >> x1;

    std::cout << "Coordenadas ponto 1 (y): ";
    std::cin >> y1;

    Sleep(SLEEP_1);

    std::cout << "Coordenadas ponto 2 (x): ";
    std::cin >> x2;

    std::cout << "Coordenadas ponto 2 (y): ";
    std::cin >> y2;

    Sleep(SLEEP_1);

    distancia = sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2));

    std::cout << "Distancia Euclidiana: " << distancia << std::endl;
}

But I still can not get what I want ...

For example:

√ (4-7) ² + (2-5) ² = 12

but the program says:

asked by anonymous 11.12.2015 / 21:28

2 answers

7

Your problem lies in this line:

distancia = sqrt(((x2 - x1) ^ 2) + ((y2 - y1) ^ 2));

In C ++, the ^ operator is not exponentiation, but the "or exclusive" (xor). You are doing the xor of the difference between the numbers and 2 , which is equivalent to changing the 2nd bit of the number and only. In C ++ there is no exponentiation operator, as far as I know, it is better to simply multiply the difference by itself:

distancia = sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
    
11.12.2015 / 21:56
6

I would do this by taking advantage of most of your code, using hypot(x,y) (only from C ++ 11) that returns the square root of the quadratic sum of x and y :

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

int main(){

    double x1, x2, y1, y2, distancia;

    cout << "Coordenadas ponto 1 (x): ";
    cin >> x1;

    cout << "Coordenadas ponto 1 (y): ";
    cin >> y1;

    cout << "Coordenadas ponto 2 (x): ";
    cin >> x2;

    cout << "Coordenadas ponto 2 (y): ";
    cin >> y2;

    distancia = hypot(x1-y1,x2-y2);

    cout << "Distancia Euclidiana: " << distancia << endl;

    return 0;

}

Note also that both coordinates of points and distance can not be integers (unless you have a discretized space). An interesting suggestion would be to write the valid code for a space with a n-dimensional Euclidean metric or for spaces with different metrics.

    
11.12.2015 / 22:39