Blue Bridge Cup Algorithm Improves 6-17 Complex Number Four Operations

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.
sample input
2 4 * -3 2
Sample output
-14-8i
sample input
3 -2 + -1 3
Sample output
2+1i

important point:

  1. To read in with double
  2. If the imaginary part is 0, the imaginary part is not output
  3. 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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325738179&siteId=291194637