1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
|
#include<iostream>
using namespace std;
class ComplexNumber {
public:
ComplexNumber( double real = 0, double imag = 0 );
double Re() const;
double Im() const;
friend ostream& operator<<( ostream& in, const ComplexNumber& b );
friend istream& operator>>( istream& in, ComplexNumber& c );
private:
double re;
double im;
};
ComplexNumber::ComplexNumber( double real, double imag ) {
re = real;
im = imag;
}
double ComplexNumber::Re() const {
return re;
}
double ComplexNumber::Im() const {
return im;
}
// Pretty prints ComplexNumbers
ostream& operator<<( ostream &out, const ComplexNumber& b ) {
bool realPrinted = false;
if (b.re != 0 || (b.re == 0 && b.im == 0)) {
out << b.re;
realPrinted = true;
}
if (b.im > 0) {
if (realPrinted) {
out << "+";
}
if (b.im != 1) {
out << b.im;
}
out << "i";
}
else if (b.im < 0) {
if (b.im == -1) {
out << "-";
}
else {
out << b.im;
}
out << "i";
}
return out;
}
// natural extraction operator for ComplexNumbers
istream& operator>> ( istream& in, ComplexNumber& z ) {
string complexText;
int plusPos, minusPos, i_Pos;
double coefficient1;
bool real, imag;
in >> coefficient1; // fails for pure imag nums converts "bi" to zero.
getline(cin,complexText);
plusPos = complexText.find('+');
minusPos = complexText.find('-');
i_Pos = complexText.find('i');
real = i_Pos < 0; // real number won't contain the character i
imag = minusPos < 0 && plusPos < 0; // pure imag number if no + or -
if (real) {
z.re = coefficient1;
z.im = 0.0;
}
else if (imag) {
z.re = 0.0;
z.im = coefficient1;
}
else {
z.re = coefficient1;
complexText.replace(i_Pos,1," ");
if (plusPos >= 0)
complexText.replace(plusPos,1," ");
if (minusPos >= 0)
complexText.replace(minusPos,1," ");
z.im = atof(complexText.c_str());
if (z.im == 0)
z.im = 1; // 1 + i, 1 - i
if (minusPos >= 0)
z.im = -z.im;
}
return in;
}
int main()
{
ComplexNumber z;
cout << "Input a Complex Number: ";
cin >> z;
cout << z.Re() << "\n" << z.Im() << "\n" << z << "\n";
return 0;
}
|