作业帮 > 综合 > 作业

求一C++程序:计算点到直线的距离?

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/29 23:28:53
求一C++程序:计算点到直线的距离?
已知点(X,Y)到直线ax+by+y=0的计算公式为:
d=|(ax+by+c)/sqrt(a^2+b^2)| .分别定义一个point类和line类,利用全局函数dist计算一个点到一个直线的距离?
一楼的:你的方法 程序都对
但没有用到我给的公式
三楼:你的初始化再那里?我没有看懂
在Windows XP+VC++6.0下编译通过并正常运行
我的测试程序是用默认参数值初始化的
当然,你可以改为:
Point P(2,3);
Line L(1,2,3);
其它的都不变
懂了么?
#include
#include
using namespace std;
class Line;//声明类Line,因为Point类中声明友元函数friend dist(Point P,Line L)用到该类
class Point
{
private:
double x;
double y;
public:
Point(double xx=0,double yy=0)
{
x=xx;
y=xx;
}
friend double dist(Point P,Line L);
};
class Line
{
private:
double a;
double b;
double c;
public:
Line(double aa=1,double bb=1,double cc=1)
{
a=aa;
b=bb;
c=cc;
}
friend double dist(Point P,Line L);
};
double dist(Point P,Line L)
{
double s;
s=(L.a*P.x+L.b*P.y+L.c)/sqrt(L.a*L.a+L.b*L.b);
if(s>0)
return s;
else
return -s;
}
int main()
{
Point P;//这相当于 Point P(0,0);
Line L;//相当于 Line L(1,1,1);
cout