用类求两点间的距离

设计一个用来表示直角坐标系的Location类,在主程序中创建类Location的两个对象A和B,要求A的坐标点在第3象限,B的坐标点在第2象限,分别采用成员函数和友元函数计算给定两个坐标点之间的距离,要求按如下格式输出结果:

A(x1,y1), B(x2,y2),

Distance1=d1

Distance2=d2

其中:x1、y1、x2、y2为指定坐标值,d1和d2为两个坐标点之间的距离。

#include<iostream>
#include<cmath>
using namespace std;
class Location
{
	public:
		Location(double a,double b);//构造函数; 
		double getx();
		double gety();
		double distance(Location &d);//成员函数 
		friend double distance1(Location &,Location &);//友元函数; 
	private:
		double x,y;
};
Location::Location(double a,double b)//构造函数定义; 
{
	x=a;
	y=b;
}
double Location:: getx()
{
	return x;
}
double Location::gety()
{
	return y;
}
double Location::distance(Location &d)
{
	double d1;
	d1=sqrt((this->x-d.x)*(this->x-d.x)+(this->y-d.y)*(this->y-d.y));
	cout<<"Distance1="<<d1<<endl;
	return 0;
}
double distance1(Location &a,Location &b)
{
	double d2;
	d2=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
	cout<<"Distance2="<<d2<<endl;
	return 0;
}
int main()
{
	Location A(-1,-1);
	Location B(-1,1);
	cout<<"A("<<A.getx()<<","<<A.gety()<<endl;
	A.distance(B);
	distance(A,B);
	return 0;
}

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值