【发布时间】: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).