计算点到直线的距离。首先设计一个点类Point,它有2 个私有数据成员x和y,表示点的坐标。另一个类为直线类Line,它有3 个私有数据成员a,b和c,表示直线方程ax+by+c= 0。这两个类中都说明了一个友元函数dist,用于计算一个点到直线的距离。
#include<iostream>
#include <cmath>
using namespace std;
class Line;
class Point {
private:
double x,y;
public:
friend void dist(Point p, Line l);
Point() {
x = 0.0;
y = 0.0;
}
void input() {
cin >> x >> y;
}
};
class Line {
private:
double a,b,c;
public:
friend void dist(Point p, Line l);
Line() {
a = 0.0;
b = 0.0;
c = 0.0;
}
void inputL() {
cin >> a >> b >> c;
if(a==0&&b==0) {
cout<<"输入错误"<<endl;
exit(0);
}
}
};
void dist(Point p, Line l) {
double c,d,e;
c = sqrt((l.a * l.a + l.b * l.b));
d = (l.a) * (p.x) + (l.b) * (p.y) + l.c;
fabs(d / c);
cout << fabs(d / c);
}
int main() {
Point p;
cout << "请输入点的横坐标,纵坐标:" << endl;
p.input();
Line l;
cout << "请输入直线的 a,b,c:" << endl;
l.inputL();
cout << "点到直线的距离为:" << endl;
dist(p, l);
return 0;
}