void Complex::display() {
cout << "(" << real << "," << imag << "i)" << endl;
}
这里你判断一下real是否等于0,如果等于0,直接cout << "(0," << imag << "i)" << endl;
#include <iostream>
#include <iomanip>
using namespace std;
class Complex {
public:
Complex(double x = 0, double y = 0) :real(x), imag(y) {}
friend Complex operator * (Complex& c1, Complex& c2);
friend Complex operator / (Complex& c1, Complex& c2);
Complex operator + (Complex& c2);
Complex operator - (Complex& c2);
void display();
private:
double real;
double imag;
};
Complex operator * (Complex& c1, Complex& c2) {
return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.real);
}
Complex operator / (Complex& c1, Complex& c2) {
Complex c;
c.real = (c1.real * c2.real + c1.imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
c.imag = (c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
return c;
}
Complex Complex ::operator + (Complex& c2) {
return Complex(real + c2.real, imag + c2.imag);
}
Complex Complex ::operator - (Complex& c2) {
return Complex(real - c2.real, imag - c2.imag);
}
void Complex::display() {
cout << "(" << real << "," << imag << "i)" << endl;
}
int main()
{
double real, imag;
cout << "first number:" << endl;
cout << "real part:" << endl;
cout << "image part:" << endl;
cout << "second number:" << endl;
cout << "real part:" << endl;
cout << "image part:" << endl;
cin >> real >> imag;
Complex c1(real, imag);
cin >> real >> imag;
Complex c2(real, imag);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
Complex c5 = c1 * c2;
Complex c6 = c1 / c2;
cout << "c1+c2="; c3.display();
cout << "c1-c2="; c4.display();
cout << "c1*c2="; c5.display();
cout <<setiosflags(ios::fixed) << setprecision(2) <<"c1/c2="; c6.display();
return 0;
}