Squareroot在C++中不返回数字

uye*_*tch 1 c++ nan math.h

在下面的程序中,我试图计算两点之间的距离.为此,我制作了两个Point对象.在返回距离的方法中,我使用距离公式来计算空间中两点之间的距离.但是,每次运行程序时,我都会得到一个不是数字值,不应该存在.请帮忙.

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>

using namespace std;

class Point
{
    public:
        Point(int a, int b);
        ~Point();
        double getDistance(Point& P2);
        void setPoints(int a, int b);
        int getX();
        int getY();
    private:
        int x;
        int y;
};

Point::Point(int a, int b)
{
    setPoints(a,b); 
}

Point::~Point()
{
    //Nothing much to do
}

void Point::setPoints(int a, int b)
{
    x = a;
    y = b;
}

double Point::getDistance(Point& P2)
{
    int xdiff = P2.getX()-this->getX();
    int ydiff = P2.getY()-this->getY();
    xdiff = xdiff*xdiff;
    ydiff = ydiff*ydiff;
    double retval =  sqrt((xdiff) - (ydiff));
    return retval;
}

int Point::getX()
{
    return x;
}

int Point::getY()
{
    return y;
}
int main(int argc, char* argv[])
{
    Point P1(0,0);
    Point P2(0,1);
    Point& pr = P2;
    cout<<P1.getDistance(pr)<<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

cra*_*gmj 6

你的公式错了.不是

sqrt(xdiff - ydiff)
Run Code Online (Sandbox Code Playgroud)

sqrt(xdiff + ydiff)
Run Code Online (Sandbox Code Playgroud)

你试图得到sqrt(-1)的确不是数字(或不是实数).