//编程实现复数四则运算。复数由实部和虚部构造,可以定义一个复数类,然后再在类中重载复数四则运算的运算符。 #include<iostream> using namespace std; class complex{ public: complex(){real=image=0;} complex(double r,double i){real=r;image=i;} complex operator +(const complex &c); complex operator -(const complex &c); complex operator *(const complex &c); complex operator /(const complex &c); friend void print(const complex &c); private: double real,image; }; inline complex complex::operator+(const complex &c){ return complex(real+c.real,image+c.image);} inline complex complex::operator-(const complex &c){ return complex(real-c.real,image+c.image);} inline complex complex::operator*(const complex &c){ return complex(real*real-image*c.image,real*c.image+image*c.real);} inline complex complex::operator/(const complex &c){ return complex((real*c.real+image*c.image)/(c.real*c.real+c.image*c.image)+ (image*c.real-real*c.image)/(c.real*c.real+c.image*c.image));} void print(const complex &c){ if(c.image<0) cout<<c.real<<c.image<<'i'; else cout<<c.real<<'+'<<c.image<<'i'; } int main(){ complex c1(2.0,3.0),c2(4.0,-2.0),c3; c3=c1+c2; cout<<"\nc1+c2="; print(c3); c3=c1-c2; cout<<"\nc1-c2="; print(c3); c3=c1*c2; cout<<"\nc1*c2="; print(c3); c3=c1/c2; cout<<"\nc1/c2="; print(c3); c3=(c1+c2)*(c1-c2)*c2/c1; cout<<"\n(c1+c2)*(c1-c2)*c2/c1="; print(c3); cout<<endl; return 0; }哪错了,怎么改正
时间: 2024-03-12 18:44:44 浏览: 45
复数的四则运算
代码本身没有错误,但是输出结果有问题。在print函数中,当虚部为负数时,应该加上括号来表示负号。修改print函数如下:
```
void print(const complex &c){
if(c.image<0)
cout<<c.real<<c.image<<"i";
else
cout<<c.real<<'+'<<'('<<c.image<<')'<<"i";
}
```
这样输出结果就正确了。
阅读全文