1051. 复数乘法 (15)
复数可以写成(A + Bi)的常规形式,其中A是实部,B是虚部,i是虚数单位,满足i2 = -1;也可以写成极坐标下的指数形式(R*e(Pi)),其中R是复数模,P是辐角,i是虚数单位,其等价于三角形式 R(cos(P) + isin(P))。
现给定两个复数的R和P,要求输出两数乘积的常规形式。输入格式:
输入在一行中依次给出两个复数的R1, P1, R2, P2,数字间以空格分隔。
输出格式:
在一行中按照“A+Bi”的格式输出两数乘积的常规形式,实部和虚部均保留2位小数。注意:如果B是负数,则应该写成“A-|B|i”的形式。输入样例:
2.3 3.5 5.2 0.4输出样例:
-8.68-8.23i
Answer:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
struct complex {
double real;
double visu;
inline complex(){}
inline complex multi(complex& c) {
double tr = this->real, tv = this->visu;
this->real = tr*c.real - tv*c.visu;
this->visu = tr*c.visu + tv*c.real;
return *this;
}
inline void exp() {
cout << fixed;
cout << setprecision(2);
if(this->real < 0 && this->real >= -0.005)
cout << "0.00";
else
cout << this->real;
if(this->visu >= 0)
cout << "+" << this->visu << "i";
else if(this->visu < 0 && this->visu > -0.005)
cout << "+0.00i";
else if(this->visu < 0)
cout << this->visu << "i";
cout << endl;
}
};
int main() {
double r1, p1, r2, p2;
cin >> r1 >> p1 >> r2 >> p2;
complex c1, c2;
c1.real = r1*cos(p1);
c1.visu = r1*sin(p1);
c2.real = r2*cos(p2);
c2.visu = r2*sin(p2);
c1.multi(c2).exp();
}
PS.
又有精度问题。