Search code examples
c++nanmath.h

Squareroot returning not a number in C++


In the program below, I am trying to calculate the distance between two points. For this, I have made two Point objects. In the method that returns the distance, I have used the distance formula to calculate distance between two points in space. However, every time I run the program, I get a not a number value, which shouldn't be there. Please help.

#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;
}

Solution

  • Your formula is wrong. It's not

    sqrt(xdiff - ydiff)
    

    but

    sqrt(xdiff + ydiff)
    

    You're trying to get the sqrt(-1) which is indeed not a number (or not a real number).