重载大于号运算符,比较复数大小

本题目要求编写代码的功能为:
输入两个复数(变量名自拟),比较复数模的大小,复数实部与虚部都是整数
要求输入时输入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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值