数据的间距问题(函数模板)
类point有两个数据成员:x和y, 分别代表x坐标和y坐标,并有若干构造函数和一个重载-(减号,计算两点距离)的成员函数。
要求设计一个函数模板
template < class T >
double dist(T a, T b)
对int,float,point或者其他类型的数据,返回间距。
输入格式:
每一行为一个操作,每行的第一个数字为元素类型,1为整型元素,2为浮点型元素,3为point类型,若为整型元素,接着输入两个整型数据,若为浮点型元素,接着输入两个浮点型数据,若为point型元素,输入两个point型数据(x1 y1 x2 y2),输入0时标志输入结束。
输出格式:
对每个输入,每行输出一个间距值。
样例输入:
1 2 5
3 2 4 5 9
2 2.2 9.9
0
样例输出:
3
5.83095
7.7
时间限制
1000 ms
内存限制
65536 kB
代码长度限制
8192 B
判题程序
Standard
作者
wang
来源
final 函数模板
#include<iostream> #include<math.h> using namespace std; class point { float x; float y; public: double operator - (point&); friend istream& operator >>(istream&,point&); }; double point::operator - (point& p) { return sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)); } istream& operator >>(istream& in,point& p) { in>>p.x>>p.y; return in; } template<class T> double dist(T a,T b) { return fabs(a-b); } int main() { int i1,i2,act; float f1,f2; point p1,p2; cin>>act; while(act) { switch(act) { case 1:cin>>i1>>i2;cout<<dist(i1,i2);break; case 2:cin>>f1>>f2;cout<<dist(f1,f2);break; case 3:cin>>p1>>p2;cout<<dist(p1,p2);break; } cout<<endl; cin>>act; } return 0; }