【PTA】计算点到直线的距离一一友元函数的应用 (20 分)

该博客展示了一个C++程序,用于计算二维空间中一个点到直线的欧几里得距离。程序定义了`point`和`line`类,并使用友元函数计算距离,确保结果在输出时精确到两位小数。当距离为0时,直接输出0而不是0.00。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述

注意:
1、若距离为0,则输出0,而非0.00;
2、友元函数的声明是要带上参数的。

#include<iostream>
#include<math.h>
using namespace std;
class point;
class line;

class point
{
	double x;
	double y;
	
	public:
		point(double a1,double b1)
		{
			x=a1;
			y=b1;
		}
		friend void dis(point &p,line &l);
};

class line
{
	double a,b,c;
		
	public:
		line(double x,double y,double z)
		{
			a=x;
			b=y;
			c=z;
		}
		friend void dis(point &p,line &l);
};

void dis(point &p,line &l)
{

	double ans=abs(p.x*l.a+l.b*p.y+l.c)/sqrt(l.a*l.a+l.b*l.b);
	cout.precision(2);
	if(ans==0) 
	{
		cout<<"The distance is: 0";
	}
	else cout<<"The distance is: "<<fixed<<ans;
}
int main()
{
	double x,y,a,b,c;
	cin>>x>>y>>a>>b>>c;
	point p(x,y);
	line l(a,b,c);
	dis(p,l);	
	return 0;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

karshey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值