复数能进行模加运算么
- 提问者网友:斩断情丝
- 2021-02-14 09:11
- 二级知识专家网友:转身→时光静好
- 2021-02-14 09:32
- 1楼网友:厭世為王
- 2021-02-14 10:19
//设计一个复数类,可以进行复数的加、减、乘、法、除、取模、乘方、求2个复数向量之间的夹角等运算。 #include <iostream> #include <cmath> #include <cstdlib> using namespace std; class complex { private: float real; float imag; public: //构造函数 complex() { real=0; imag=0; } complex(float a,float b):real(a),imag(b){} //复数输出 void display(); //取模运算 float mode(); //复数的四则运算 complex operator+(complex &a); complex operator-(complex &a); complex operator*(complex &a); complex operator/(complex &a); //复数乘方 complex power(int n); //计算夹角 float includedangle(complex &a); }; void complex::display () { cout<<"this complex is:"; if(imag>=0) cout<<real<<'+'<<imag<<'i'<<endl; else cout<<real<<imag<<'i'<<endl; cout<<"mode is:"<<mode()<<endl; } float complex::mode() { return (sqrt(real*real+imag*imag)); }
complex complex::operator+(complex &a) { complex temp; temp.real = real + a.real ; temp.imag = imag + a.imag ; return temp; } complex complex::operator-(complex &a) { complex temp; temp.real =real - a.real ; temp.imag =imag - a.imag ; return temp ; } complex complex::operator*(complex &a) { complex temp; temp.real = real*a.real - imag*a.imag; temp.imag = real*a.imag + a.real*imag; return temp; } complex complex::operator/(complex &a) { complex temp; if(a.real!=0 && a.imag!=0) { cout<<"error!"<<endl; } else { temp.real = (real*a.real - imag*(-a.imag))/(a.real*a.real + a.imag*imag); temp.imag = (real*(-a.imag) + a.real*imag)/(a.real*a.real + a.imag*imag); } return temp; } complex complex::power (int n) { complex temp; temp=*this; for(int i=1;i<n;i++) { temp=(*this)*temp; } return temp; } float complex::includedangle(complex &a) { //tanθ=|(k2- k1)/(1+ k1*k2)| float b,k1,k2; if(real!=0 && a.real!=0) { k1=imag/real; k2=a.imag/a.real; b=atan(fabs((k2-k1)/(1+k1*k2))); } else if(real==0 && a.real!=0) { k2=a.imag/a.real; b=atan(fabs(k2)); } else if(real!=0 && a.real==0) { k1=imag/real; b=atan(fabs(k1)); } else b=0; return b; }