设计符合下述要求的Complex复数类,使得下述程序可以正常运行:自定义>操作符函数,使得两个复数对象可以通过>操作符以“模”为基础进行大小比较。
要求:Complex的实部和虚部成员均使用double类型。
裁判测试程序样例:
#include <iostream> #include <cmath> using namespace std; //此处定义Complex类其及operator>()自定义操作符函数 int main() { const int N = 10; Complex a[N]; for (int i=0;i<N;i++) cin >> a[i].dReal >> a[i].dImage; //使用冒泡排序算法进行排序 for (int i=N-1;i>0;i--) for (int j=0;j<i;j++){ if (a[j]>a[j+1]){ auto t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } printf("Sorted array of complexes:\n"); for (int i=0;i<N;i++) printf("(%.1f,%.1f),",a[i].dReal,a[i].dImage); return 0; }
输入样例:
1.1 3.3
2.3 2.1
7.4 7.6
6.1 0.1
4.4 4.4
5.6 7.8
10.1 23.2
0.1 0.2
56.12 78.2
4.2 2.1
说明:依次输入10个复数的实部和虚部
输出样例:
Sorted array of complexes:
(0.1,0.2),(2.3,2.1),(1.1,3.3),(4.2,2.1),(6.1,0.1),(4.4,4.4),(5.6,7.8),(7.4,7.6),(10.1,23.2),(56.1,78.2),
请注意:函数题只需要提交相关代码片段,不要提交完整程序。
class Complex {
public:
double dReal, dImage;
bool operator> (Complex& a)
{
double n = sqrt(pow(dReal, 2) + pow(dImage, 2)); //千万记住n,m是double类型!!!
double m = sqrt(pow(a.dReal, 2) + pow(a.dImage, 2));
if (n > m) //当n大于m的时候返回true执行排序,否则不调换位置不执行冒泡排序。
return 1;
else
return 0;
}
};