7-1 2017final函数模板 (20 point(s))
数据的间距问题(函数模板) 类point有三个数据成员:x、y和z, 分别代表x坐标、y坐标和z坐标,并有若干构造函数和一个重载-(减号,计算两点距离)的成员函数。 要求设计一个函数模板,
template < class T> double dist(T a, T b)
对int,float,point或者其他类型的数据,返回间距。
输入格式:
每一行为一个操作,每行的第一个数字为元素类型,1为整型元素,2为浮点型元素,3为point类型,若为整型元素,接着输入两个整型数据,若为浮点型元素,接着输入两个浮点型数据,若为point型元素,输入两个point型数据(x1 y1 z1 x2 y2 z2),输入0时标志输入结束。
输出格式:
对每个输入,每行输出一个间距值。
输入样例:
1 2 5
3 2 4 7 5 9 7
2 2.2 9.9
0
输出样例:
3
5.83095
7.7
收获
- 用switch会超,不知原因,尽量用if吧,已解决,使用switch时记得要在每种case里加break。
#include<iostream>
#include<cmath>
using namespace std;
class point{
private:
double x,y,z;
public:
point(double a=0,double b=0,double c=0):x(a),y(b),z(c){};
double operator-(const point &p){
float dx=x-p.x;
float dy=y-p.y;
float dz=z-p.z;
double distance=sqrt(dx*dx+dy*dy+dz*dz);
return distance;
}
};
template<class T>
double dist(T a,T b){
return abs(a-b);
}
int main(){
int n;
cin>>n;
while(1){
if(n==0){
break;
}
switch(n){
case 1:{
int x1,x2;
cin>>x1>>x2;
cout<<dist(x1,x2)<<endl;
cin>>n;
break;
}
case 2:{
float x1,x2;
cin>>x1>>x2;
cout<<dist(x1,x2)<<endl;
cin>>n;
break;
}
case 3:{
double x1,y1,z1,x2,y2,z2;
cin >> x1 >> y1 >> z1 >> x2 >> y2 >> z2;
point p1=point(x1,y1,z1),p2=point(x2,y2,z2);
cout<<dist(p1,p2)<<endl;
cin>>n;
break;
}
default:{
break;
}
}
}
// while(1){
// if(n==0){
// break;
// }
// if(n==1){
// int x1,x2;
// cin>>x1>>x2;
// cout<<dist(x1,x2)<<endl;
// cin>>n;
// }else if(n==2){
// float x1,x2;
// cin>>x1>>x2;
// cout<<dist(x1,x2)<<endl;
// cin>>n;
// }
// else{
// double x1,y1,z1,x2,y2,z2;
// cin >> x1 >> y1 >> z1 >> x2 >> y2 >> z2;
// point p1=point(x1,y1,z1),p2=point(x2,y2,z2);
// cout<<dist(p1,p2)<<endl;
// cin>>n;
// }
// }
return 0;
}