3 回答
TA贡献1772条经验 获得超5个赞
#include<iostream>
#include<math.h>
class Location
{
public:
Location(double xx,double yy):x(xx),y(yy){}//构造
double Getx(){return x;}
double Gety(){return y;}//最后用于返回坐标
double distance(Location & locationItem);//就是这个
friend double distance(Location &,Location &);//用友元函数求距离
private:
double x,y;//坐标
};
double Location::distance(Location & locationItem)
{
double l;
l=sqrt(pow(x-locationItem.Getx(),2)+pow(y-locationItem.Gety(),2));
return l;
}
double distance(Location &locationItem1,Location &locationItem2)
{//这个函数是友元的,可以下面两种方法。
double l;
// l=sqrt(pow(locationItem1.Getx()-locationItem2.Getx(),2)+pow(locationItem1.Gety()-locationItem2.Gety(),2));
l=sqrt(pow(locationItem1.x-locationItem2.x,2)+pow(locationItem1.y-locationItem2.y,2));
return l;
}
int main()
{
Location locationItem1(8,9);
Location locationItem2(5,5);
double result;
result=distance(locationItem1,locationItem2);
std::cout<<result<<std::endl;
result=locationItem1.distance(locationItem2);
std::cout<<result<<std::endl;
result=locationItem2.distance(locationItem1);
std::cout<<result<<std::endl;
return 0;
}
这很明白了。应该没问题了吧?
你建个工程,直接复制我的代码,而且还是按你的改的。能运行。然后自己再看。
TA贡献1893条经验 获得超10个赞
给你写了个函数,你试试看,需要包含math.h
全局函数版本
double distance(Location const& a, Location const& b)
{
double dx = a.GetX() - b.GetX();
double dy = a.GetY() - b.GetY();
return sqrt(dx * dx + dy * dy);
}
成员变量版本
double Location::distance(Location const& b) const
{
double dx = GetX() - b.GetX();
double dy = GetY() - b.GetY();
return sqrt(dx * dx + dy * dy);
}
TA贡献2080条经验 获得超4个赞
#include <iostream>
#include <math.h>
using namespace std;
class Location
{
public:
Location(double,double);//构造
double Getx();
double Gety();//最后用于返回坐标
double distance(Location &);//就是这个
friend double distance(Location &,Location &);//用友元函数求距离
private:
double x,y;//坐标
};
Location::Location(double x1,double y1)
{
x=x1;
y=y1;
}
double Location:: distance(Location &p)
{
double dx=x-p.Getx();
double dy=x-p.Gety();
double d=0;
d=sqrt( pow(dx,2)+ pow(dy,2 ) );
return d;
}
double Location:: Getx()
{
return x;
}
double Location:: Gety()
{
return y;
}
double distance(Location &p1,Location &p2)
{
double d=sqrt( pow((p1.Getx()-p2.Getx()),2)+pow((p2.Gety()-p2.Gety()),2) );
return d;
}
int main()
{
Location p1(3,5);
Location p2(10,20);
double dist=0.0;
dist=p2.distance(p1);
cout << "p1("<<p1.Getx()<<","<<p1.Gety()<<") and p2("<<p2.Getx()<<","<<p2.Gety()<<") distance is :" << dist <<endl; getchar();
return 0;
}
运行结果:
p1(3,5) and p2(10,20) distance is :8.60233
- 3 回答
- 0 关注
- 134 浏览
添加回答
举报