复数可以写成 (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
- 刚开始我以为这么简单就行了,结果这个代码没有考虑到输出格式的问题
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
double r1,p1,r2,p2,w1,w2,w3,w4,w5,result1,result2;
cin>>r1>>p1>>r2>>p2;
w1=r1*r2;
w2=cos(p1)*cos(p2);
w3=cos(p1)*sin(p2);
w4=cos(p2)*sin(p1);
w5=sin(p1)*sin(p2);
result1=w1*(w2-w5);
result2=w1*(w3+w4);
printf("%.2f%.2fi",result1,result2);
return 0;
}
- 最终代码
- 要考虑到四舍五入的情况,若A或B>-0.05且<0时,四舍五入会出现-0.00,这种情况应该排除
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
double r1,p1,r2,p2,w1,w2,w3,w4,w5,result1,result2;
cin>>r1>>p1>>r2>>p2;
w1=r1*r2;
w2=cos(p1)*cos(p2);
w3=cos(p1)*sin(p2);
w4=cos(p2)*sin(p1);
w5=sin(p1)*sin(p2);
result1=w1*(w2-w5);
result2=w1*(w3+w4);
if (result1 < 0 && result1 > -0.005) {
result1 = 0.00;
}
if (result2 < 0 && result2 > -0.005) {
result2 = 0.00;
}
printf("%.2f%+.2fi\n", result1,result2);// %+:有符号,值若>=0,在值前显示加号;若为负,则在值前显示负号
//printf("%.2f%.2fi",result1,result2);
return 0;
}