C++实例练习:Complex(类与对象+构造)

编写一个复数类,能实现加、减运算,能输出复数的信息。 要求至少包含以下方法:

1、缺省(无参)构造函数,设置实部与虚部为1;

2、有参构造函数,给实部与虚部赋值;

3、加法运算,计算两个复数的和;

4、减法运算,计算两个复数的差;

5、输出方法,输出当前复数的值

输入

测试数据的组数t 第一组的两个复数的实部 虚部 实部 虚部 第二组的两个复数的实部 虚部 实部 虚部 …

4
2 1 2 1
2 1 2 -1
3 1 2 -6
3 3 2 2

输出

第一组两个复数的和 第一组两个复数的差

sum:4+2i
remainder:0
sum:4
remainder:2i
sum:5-5i
remainder:1+7i
sum:5+5i
remainder:1+i


```cpp
#include<iostream>
using namespace std;
class Complex {
private:
    int real;
    int imaginary;
public:
    int getReal() {
        return real;
    }
    int getImaginary() {
        return imaginary;
    }
    Complex() {
        real = 1;
        imaginary = 1;
    }
    Complex(int r, int i) {
        real = r;
        imaginary = i;
    }
    void sum(Complex& a, Complex& b) {
        real = a.getReal() + b.getReal();
        imaginary = a.getImaginary() + b.getImaginary();
    }
    void remainder(Complex& a, Complex& b) {
        real = a.getReal() - b.getReal();
        imaginary = a.getImaginary() - b.getImaginary();
    }
    void print() {
        if (real == 0 && imaginary == 0) {
            cout << "0" << endl;
        }
        else if (real == 0 && imaginary != 0) {
            cout << imaginary << "i" << endl;
        }
        else if (real != 0 && imaginary == 0) {
            cout << real << endl;
        }
        else if (real != 0 && imaginary > 0 && imaginary!=1) {
            cout << real <<"+" << imaginary << "i" << endl;
        }
        else if(real != 0 && imaginary == 1) {
            cout << real << "+" << "i" << endl;
        }
        else {
            cout << real << imaginary << "i" << endl;
        }
    }
};
 
int main() {
    Complex c;
    int t, x, y, m, n;
    cin >> t;
    while (t--) {
        cin >> x >> y >> m >> n;
        Complex a,b;
        a = Complex(x, y);
        b = Complex(m, n);
        c.sum(a, b);
        cout << "sum:";
        c.print();
        c.remainder(a, b);
        cout << "remainder:";
        c.print();
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值