Original title link: http://lx.lanqiao.cn/problem.page?gpid=T255
Welcome to my Blue Bridge Cup OJ Problem Solution~ https://blog.csdn.net/richenyunqi/article/details/80192062
Algorithm improvement 6-17 Four arithmetic operations on complex numbers
Time limit: 1.0s Memory limit: 512.0MB
Design a complex number library to implement basic complex number addition, subtraction, multiplication and division operations.
When inputting, just type the real part and the imaginary part separately, separate them with spaces, and separate the two complex numbers with an operator; when outputting, print the result on the screen in the format of a+bi. See sample input and sample output.
Note that the special case is considered, and the string "error" is output when the calculation cannot be performed.
When inputting, just type the real part and the imaginary part separately, separate them with spaces, and separate the two complex numbers with an operator; when outputting, print the result on the screen in the format of a+bi. See sample input and sample output.
Note that the special case is considered, and the string "error" is output when the calculation cannot be performed.
sample input
2 4 * -3 2
Sample output
-14-8i
sample input
3 -2 + -1 3
Sample output
2+1i
important point:
- To read in with double
- If the imaginary part is 0, the imaginary part is not output
- Do division if the real and imaginary parts of the second imaginary number are both 0, output error
c++ code:
#include<bits/stdc++.h> using namespace std; int main(){ pair<int,int>A,B,C; char c; scanf("%d%d %c %d%d",&A.first,&A.second,&c,&B.first,&B.second); if(c=='+'){ C.first=A.first+B.first; C.second=A.second+B.second; }else if(c=='-'){ C.first=A.first-B.first; C.second=A.second-B.second; }else if(c=='*'){ C.first=A.first*B.first-A.second*B.second; C.second=A.first*B.second+A.second*B.first; }else if(c=='/'){ if(B.first==0&&B.second==0){ printf("error"); return 0; } C.first=(A.first*B.first+A.second*B.second)/(B.first*B.first+B.second*B.second); C.second=(A.second*B.first-A.first*B.second)/(B.first*B.first+B.second*B.second); } printf("%d%s",C.first,C.second>0?"+":""); if(C.second!=0) printf("%di",C.second); return 0; }