编写一个复数类,能实现加、减运算,能输出复数的信息。 要求至少包含以下方法:
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();
}
}