数据的间距问题
复数类Complex有两个数据成员:a和b, 分别代表复数的实部和虚部,并有若干构造函数和一个重载-(减号,用于计算两个复数的距离)的成员函数。 要求设计一个函数模板
template < class T >
double dist(T a, T b)
对int,float,Complex或者其他类型的数据,返回两个数据的间距。
以上类名和函数模板的形式,均须按照题目要求,不得修改
1 #include<iostream> 2 #include<cmath> 3 using namespace std; 4 5 class Complex 6 { 7 private: 8 double a, b; 9 public: 10 Complex() 11 { 12 a = 0, b = 0; 13 } 14 Complex(double A, double B) 15 { 16 a = A, b = B; 17 } 18 void set(double A, double B) 19 { 20 a = A, b = B; 21 } 22 void display() 23 { 24 cout << a << " " << b << endl; 25 } 26 friend double operator - (Complex C1, Complex C2); 27 }; 28 29 double operator -(Complex C1, Complex C2) 30 { 31 return sqrt(pow(C1.a - C2.a, 2.0) + pow(C1.b - C2.b, 2.0)); 32 } 33 34 template<class T> 35 double dist(T a, T b) 36 { 37 return abs(a - b); 38 } 39 40 int main() 41 { 42 int flag; 43 44 while(cin >> flag, flag != 0) 45 { 46 if(flag == 1) 47 { 48 int a, b; 49 cin >> a >> b; 50 cout << dist(a, b) << endl; 51 } 52 else if(flag == 2) 53 { 54 float a, b; 55 cin >> a >> b; 56 cout << dist(a, b) << endl; 57 } 58 else if(flag == 3) 59 { 60 Complex a, b; 61 double a1, a2, b1, b2; 62 cin >> a1 >> a2 >> b1 >> b2; 63 a.set(a1, a2), b.set(b1, b2); 64 cout << dist(a, b) << endl; 65 } 66 } 67 68 return 0; 69 }