C8-1 complex addition, subtraction, multiplication and division (100 / 100 points)
Title Description
Find the addition, subtraction, multiplication and division of two complex numbers.
Input description
Two numbers of double type in the first row represent the real part and virtual part of the first complex number
In the second line, two numbers of double type represent the real part and virtual part of the second complex number
Output description
The output calculates the addition, subtraction, multiplication and division of two complex numbers in turn, one line and one result
Output complex number first real part, space, then virtual part,
sample input
1 1
3 -1
sample output
4 0
-2 2
4 2
0.2 0.4
thinking
First of all, we need to know the formula of complex addition and subtraction (given) multiplication and division
If c1=a+bi, c2=c+di,
Then their product (a+bi)(c+di)=(ac bd)+(bc+ad)i;
Their quotient (AC + BD) / (c * 2 + D * 2) + J (BC AD) / (c * 2 + D * 2);
code implementation
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
class Complex {
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {};
Complex operator+ (const Complex &c2) const;
Complex operator- (const Complex &c2) const;
/*Implement the following three functions*/
Complex operator* (const Complex &c2) const;
Complex operator/ (const Complex &c2) const;
friend ostream & operator<< (ostream &out, const Complex &c);
private:
double real;
double imag;
};
Complex Complex::operator+ (const Complex &c2) const {
return Complex(real + c2.real, imag + c2.imag);
}
Complex Complex::operator- (const Complex &c2) const {
return Complex(real - c2.real, imag - c2.imag);
}
Complex Complex::operator*(const Complex &c2) const {
return Complex(real*c2.real - imag * c2.imag, imag*c2.real + real * c2.imag);
}
Complex Complex::operator/(const Complex &c2) const {
return Complex((real*c2.real + imag * c2.imag) / (c2.real*c2.real + c2.imag*c2.imag), (imag*c2.real - real * c2.imag) / (c2.real*c2.real + c2.imag*c2.imag));
}
ostream & operator<<(ostream &out, const Complex &c) {
cout << c.real << " " << c.imag << endl;
return out;
}
int main() {
double real, imag;
cin >> real >> imag;
Complex c1(real, imag);
cin >> real >> imag;
Complex c2(real, imag);
cout << c1 + c2;
cout << c1 - c2;
cout << c1 * c2;
cout << c1 / c2;
return 0;
}
Be careful
Adding const to an inner class function means that the inner class member variables will not be changed, and the outer input variables may still be changed. Therefore, const should be added to the parameter list when necessary;
After ostream & in order to ensure that the type of return value is a reference, although it is overloaded, try to keep the type of return value unchanged, such code is relatively standard;
Complex (return value type): operator + (const complex & C2);
Use of & for
1. Need to change a variable value in the function
2. No extra copy (no call to copy constructor)