PTA 复数四则运算

时间:2022-02-07 15:32:26

本题要求编写程序,计算2个复数的和、差、积、商。

输入格式:

输入在一行中按照a1 b1 a2 b2的格式给出2个复数C1=a1+b1i和C2=a2+b2i的实部和虚部。题目保证C2不为0。

输出格式:

分别在4行中按照(a1+b1i) 运算符 (a2+b2i) = 结果的格式顺序输出2个复数的和、差、积、商,数字精确到小数点后1位。如果结果的实部或者虚部为0,则不输出。如果结果为0,则输出0.0。

输入样例1:

2 3.08 -2.04 5.06

输出样例1:

(2.0+3.1i) + (-2.0+5.1i) = 8.1i
(2.0+3.1i) - (-2.0+5.1i) = 4.0-2.0i
(2.0+3.1i) * (-2.0+5.1i) = -19.7+3.8i
(2.0+3.1i) / (-2.0+5.1i) = 0.4-0.6i

输入样例2:

1 1 -1 -1.01

输出样例2:

(1.0+1.0i) + (-1.0-1.0i) = 0.0
(1.0+1.0i) - (-1.0-1.0i) = 2.0+2.0i
(1.0+1.0i) * (-1.0-1.0i) = -2.0i
(1.0+1.0i) / (-1.0-1.0i) = -1.0
对这类题目还是很犯浑等天梯赛回来,在改进代码
 #include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <queue>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <vector>
#include <set>
using namespace std;
const int minn=1e-;
double trans(double n){
double zhi;
if(n->=minn)
zhi=(int)(n*+0.5)/10.0;
else zhi=(int)(n*-0.5)/10.0;
return zhi;
} void printff(double a,double b,double c,double d,char s){
printf("(%.1f",a);
if(b>=) printf("+");
printf("%.1fi)",b);
printf(" %c ",s);
printf("(%.1f",c);
if(d>=) printf("+");
printf("%.1fi)",d);
printf(" = ");
}
void shuchu(double shi,double xu){
if(fabs(shi)<1e-&&fabs(xu)<1e-) printf("0.0\n");
else if(fabs(shi)<1e-&&fabs(xu)>1e-) printf("%.1fi\n",xu);
else if(fabs(shi)>1e-&&fabs(xu)<1e-) printf("%.1f\n",shi);
else
{
printf("%.1f",shi);
if(xu>) printf("+");
printf("%.1fi\n",xu);
}
}
int main()
{
double a1,b1,a2,b2,a3,b3,a4,b4;
double shi,xu;
scanf("%lf%lf%lf%lf",&a1,&b1,&a2,&b2);
a3=trans(a1),b3=trans(b1),a4=trans(a2),b4=trans(b2);
printff(a3,b3,a4,b4,'+');
shi=a1+a2,xu=b1+b2;
shuchu(shi,xu); printff(a3,b3,a4,b4,'-');
shi=a1-a2,xu=b1-b2;
shuchu(shi,xu); printff(a3,b3,a4,b4,'*');
shi=a1*a2+(b1*b2*(-1.0)),xu=a1*b2+b1*a2;
shuchu(shi,xu); printff(a3,b3,a4,b4,'/');
shi=(a1*a2+b1*b2)*1.0/(a2*a2+b2*b2),xu=(a2*b1-a1*b2)*1.0/(a2*a2+b2*b2);
shuchu(shi,xu);
return ;
}