本题目要求编写代码的功能为:
输入两个复数(变量名自拟),比较复数模的大小,复数实部与虚部都是整数
要求输入时输入4个整数,分别代表复数1的实部、虚部,复数2的实部虚部输入格式:
在同一行中输入4个整数,分别代表复数1的实部、虚部,复数2的实部虚部
输出格式:
输出比较两个复数模的大小的结果:
当复数1模大于复数2时 输出1
当复数1模小于复数2时 输出-1
当复数1模等于复数2时 输出0输入样例:
例如:输入复数1为 12+34i,复数2为 58+59i 时格式如下
12 34 58 59
输出样例:
复数1模小于复数2的模,所以输出-1
-1
#include <iostream>
#include <cmath>
using namespace std;
class COMPLEX {
private:
int real; // 实部
int imag; // 虚部
public:
// 构造函数
COMPLEX(int r = 0, int i = 0) : real(r), imag(i) {}
// 计算复数的模
double magnitude() const {
return sqrt(real * real + imag * imag);
}
// 重载大于号运算符,比较两个复数的模
bool operator>(const COMPLEX& other) const {
return this->magnitude() > other.magnitude(); //当前对象的模比较传入对象的模
}
// 重载小于号运算符,比较两个复数的模
bool operator<(const COMPLEX& other) const {
return this->magnitude() < other.magnitude();
}
// 重载等于号运算符,比较两个复数的模
bool operator==(const COMPLEX& other) const {
return this->magnitude() == other.magnitude();
}
};
int main() {
int real1, imag1, real2, imag2;
// 输入四个整数,分别表示两个复数的实部和虚部
cin >> real1 >> imag1 >> real2 >> imag2;
// 创建两个复数对象
COMPLEX c1(real1, imag1);
COMPLEX c2(real2, imag2);
// 比较两个复数的模并输出结果
if (c1 > c2) {
cout << 1 << endl;
} else if (c1 < c2) {
cout << -1 << endl;
} else {
cout << 0 << endl;
}
return 0;
}