【问题标题】:Why this program is giving nan is the distance between the points?为什么这个程序给出 nan 是点之间的距离?
【发布时间】:2022-01-11 10:05:27
【问题描述】:

为什么这个程序给出的是点之间的距离? 我已经使用朋友函数和 oop 概念,但是每当我尝试找到坐标之间的距离时,它显示的不是 nan 的零

#include<iostream>
#include<cmath>
using namespace std;
class point{
    int x,y;
    friend void disCoord(point,point);
    public:
    point(int a,int b){
        x=a;
        y=b;
    }
    void displaypoint(){
        cout<<"the point is("<<x<<","<<y<<")"<<endl;
    }

};//END OF CLASS
void disCoord(point o1,point o2){
    double dis=sqrt(pow(o2.x-o1.x,2)-pow(o2.y-o1.y,2));
    cout<<"The distance between point"<<"("<<o1.x<<","<<o1.y<<") and point"<<"("<<o2.x<<"," 
<<o2.y<<") is "<<dis<<endl;
}


int main(){
    point A=point(1,2);
    point B=point(1,3);
    A.displaypoint();
    B.displaypoint();
    disCoord(A,B);

return 0;
}

【问题讨论】:

  • 使用的公式有误。
  • point A=point(1,2); point B=point(1,3); 将其更改为 --> point A(1,2); point B(1,3);。无需创建不必要的临时对象,
  • 勾股定理:a^2 + b^2 = c^2。您正在尝试找到c,它是一个三角形的斜边,其腿是两点之间 X 和 Y 的差值。所以,c = sqrt(a^2 + b^2).

标签: c++ oop friend


【解决方案1】:

问题是您使用了不正确的公式,导致取负数的平方根。特别是,在你的情况下

dis = sqrt((1-1)2 - (3-2)2)

= sqrt(0 - 1) = sqrt(-1)

我引用nan documentation

NaN 值用于标识浮点元素的未定义或不可表示的值,例如负数的平方根或 0/0 的结果。

解决此问题,请将double dis=sqrt(pow(o2.x-o1.x,2)-pow(o2.y-o1.y,2)); 替换为:

double dis=sqrt(pow(o2.x-o1.x,2) + pow(o2.y-o1.y,2));

请注意,当您出于某种原因使用 - 时,中间有一个 +

这是因为计算距离的实际(正确)公式是:

d(P,Q) = sqrt((x2-x1)2 + (y2 sub>-y1)2)

【讨论】:

  • 更好的是,使用hypot()
  • 其实hypot 比较慢,但它可以正确处理非常大的数字。
【解决方案2】:

正如其他人所说,您使用的公式不正确。但是,您得到NaN0 结果的原因稍微复杂一些。

您的测试点(1,2)(1,3) 共享相同的X 组件。所以,你的公式:

double dis=sqrt(pow(o2.x-o1.x,2)-pow(o2.y-o1.y,2));

决议:

dis = sqrt(pow(1-1,2) - pow(3-2,2))

dis = sqrt(0 - 1)

我们都亲切地称为i-1 的平方根。这是少数会(正确)产生NaN 结果的情况之一。 (NAN 的意思是“不是数字”,以防不清楚。)

正确的距离公式:

sqrt(pow(o2.x-o1.x,2) + pow(o2.y-o1.y,2))

不允许对sqrt 使用否定参数,因此这永远不会发生。

如果您不确定要查找的内容,则很难找到这些问题。如果你没有在一行中做所有事情,调试起来会更容易:

double a2 = pow(o2.x-o1.x,2);
double b2 = pow(o2.y-o1.y,2);
double c2 = a2 + b2;
double c = sqrt(c2);

这过于冗长,但总体思路是将复杂语句拆分为组件。它更易于阅读、更易于调试,而且,如果您这样做了,您会看到 c2 是否定的。

空格很便宜,回车不花钱。不要为了节省时间而吝啬击键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2022-01-18
    相关资源
    最近更新 更多