2017-02-05 12 views
0
#include <iostream> 
#include <cmath> 

using namespace std; 
class point{ // define point class 
private: 
    float x=0; 
    float y=0; 

public: 
    point();// default constructor 
    point(float, float);// constructor 
    void setX(float); 
    void setY(float); 
    double getX()const; 
    double getY()const;  

}; 
//implement all the member function 
point::point(){ } 
point::point(float i, float k){ 
    x=i; 
    y=k; 
} 
void point::setX(float xc){ 
    x=xc; 
} 

void point::setY(float yc){ 
    y=yc; 
} 

double point::getY()const{ 
    return y; 
} 

double point::getX()const{ 
    return x; 
} 

double operator + (const point&lhs, const point &rhs) // free function. 
{ 
    double dx=lhs.getX()-rhs.getX(); 
    double dy=lhs.getX()-rhs.getY(); 
    return sqrt(dx*dx+dy*dy); 
} 
int main(){ 
    point p1(2, -1); 
    point p2(1, 5); 
    int dist=0; 
    dist = p1 + p2; 
    cout << "The distance between p1 " << "and p2" << " is " << dist << endl; 
    return 0; 
} 

Это должно быть 5, но я получил 3. Я не понимаю, почему?Point класс. формулу расстояния. логическая проблема при подключении координаты от конструктора и получения неправильного результата

ответ

0

заменить

double dy=lhs.getX()-rhs.getY(); 

по

double dy=lhs.getY()-rhs.getY() 
+0

спасибо это работает! –

+0

Рад помочь вам! Пожалуйста, вы можете принять ответ. Благодарю. – Thierry