Squareroot在C ++中不返回数字 [英] Squareroot returning not a number in C++

查看:62
本文介绍了Squareroot在C ++中不返回数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您的公式有误.不是

sqrt(xdiff - ydiff)

但是

sqrt(xdiff + ydiff)

您要获取的sqrt(-1)确实不是数字(或不是实数).

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

这篇关于Squareroot在C ++中不返回数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆