点到直线的距离

本文介绍了如何在C++中定义Point和Line类,通过友元函数计算点到直线的欧几里得距离,给定点和直线的坐标参数。
摘要由CSDN通过智能技术生成

计算点到直线的距离。首先设计一个点类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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值