6-2 复数的加法*

作者 李祥

单位 湖北经济学院

请设计复数类COMPLEX,实现复数的输入、输出和加法运算。

#include <iostream>
#include <iomanip>
using namespace std;

/* 你提交的代码将被嵌在这里 */

int main()
{
    COMPLEX a, b, c;
    cin >> a >> b;
    c = a + b;
    cout << c << endl;
    return 0;
}
输入样例
3.2+4.9i
2.5-7.3i

输出样例
5.7-2.4i

class COMPLEX {
    friend istream& operator>>(istream& cin, COMPLEX& a);
    friend ostream& operator<<(ostream& cout, COMPLEX& a);
public:
    double m_a;
    double m_b;
    COMPLEX(double a = 0, double b = 0)
    {
        m_a = a;
        m_b = b;
    }
    COMPLEX operator+(COMPLEX& a)
    {
        COMPLEX temp;
        temp.m_a = this->m_a + a.m_a;
        temp.m_b = this->m_b + a.m_b;
        return temp;
    }

};
COMPLEX operator+(COMPLEX& a, double b)
{
    COMPLEX temp;
    temp.m_a = a.m_a + b;
    temp.m_b = a.m_b;
    return temp;
}
COMPLEX operator+(double b, COMPLEX& a)
{
    COMPLEX temp;
    temp.m_a = a.m_a + b;
    temp.m_b = a.m_b;
    return temp;
}
istream& operator>>(istream& cin, COMPLEX& a)
{
    char i;
    cin >> a.m_a >> a.m_b >> i;
    return cin;
}
ostream& operator<<(ostream& cout, COMPLEX& a)
{
    cout << a.m_a;
    if (a.m_b < 0)
    {
        cout << a.m_b << 'i';
    }
    else
    {
        cout << "+" << a.m_b << 'i';
    }
    return cout;
}//喜欢就关注我吧,我是来自泉州师范学院22计算机你辉哥qaq

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值