1

在下面的程序中,我试图计算两点之间的距离。为此,我制作了两个 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;
}
4

4 回答 4

7

你的公式是错误的。它不是

sqrt(xdiff - ydiff)

sqrt(xdiff + ydiff)

你试图得到sqrt(-1)这确实不是一个数字(或不是一个实数)。

于 2012-01-21T04:22:35.587 回答
3

以下是如何为自己解决这类问题,或者至少更接近一个好的 StackOverflow 问题:

你知道问题出在sqrt()通话中。那么,它被称为什么?在这种情况下,您可以手动跟踪计算:

int xdiff = P2.getX()-this->getX();    // this is 0 - 0, which is 0.
int ydiff = P2.getY()-this->getY();    // this is 1 - 0, which is 1.
xdiff = xdiff*xdiff;                   // this is still 0.
ydiff = ydiff*ydiff;                   // this is still 1.
double retval =  sqrt((xdiff) - (ydiff));  // this is sqrt(0 - 1), or sqrt(-1).

或者,在更复杂的情况下——为了检查你的工作,你可以使用调试器打印出参数的值,或者你可以插入打印语句:

xdiff = xdiff*xdiff;
ydiff = ydiff*ydiff;
cout << 'xdiff: ' << xdiff << ' ydiff: ' << ydiff << endl
cout << 'computing sqrt(' << xdiff - ydiff << ')' << endl
double retval =  sqrt((xdiff) - (ydiff));

无论哪种方式,您现在都知道您正在计算sqrt(-1),您可以尝试直接运行它以确认它确实产生了相同的结果。所以要么你有一个“为什么要sqrt(-1)回来NaN?”的问题。或“为什么我的距离计算试图计算负数的平方根”的问题?

Hopefully you already know the answer to the first question, and the second question should indicate that you need to double-check your distance formula, which should have showed you the answer pretty quickly -- but even if you can't figure out why it's doing that, it at least makes a more useful question to ask here.

于 2012-01-21T05:50:24.927 回答
1

您应该在此处添加,而不是减去:

double retval =  sqrt((xdiff) - (ydiff));  // correct is +

由于输入数据不是(实数)数字,因此减法会导致您取 -1 的平方根。

于 2012-01-21T04:21:26.860 回答
1

正如 craigmj 所说,距离的公式是 sqrt ((x1-x2) + (y1-y2))。是加法不是减法。您所做的是生成一个会导致错误的虚数 (sqrt (-1))。

只是一个建议,但如果它不做任何事情就不要创建析构函数;将为您提供一个析构函数。添加一个不做任何事情的析构函数只会添加不需要的代码并使其看起来更混乱。

同样在getDistance函数中,不需要使用this->getX()和this->getY()。由于这是一个成员函数,它可以访问私有数据,因此您可以通过 x 和 y 直接访问变量。

于 2012-01-21T04:31:35.623 回答