#include<bits/stdc++.h>
using namespace std;
int n;
complex<double> c;
void inputComplex(complex<double> &cplx){
bool sgn, inpnum; //0:pos, 1:neg
double num, dec; //num:读入的数(不含符号位), dec:decimal小数点后的
cplx.real(0); //先初始化实部虚部为0
cplx.imag(0);
char x = getchar(); //开始读取
while (x!='-'&&x!='i'&&(x<'0'||x>'9')) x = getchar(); //不读取无关符号
while (x=='-'||x=='+'||x=='i'||(x>='0'&&x<='9')){ //当读取到了有关符号,若读取到无关符号再退出循环
sgn = 0; //一开始符号位为正
if (x=='-'){ //读取符号位
sgn = 1;
x = getchar();
}else if (x=='+') x = getchar();
num = 0; //一开始数字位为0
inpnum = false; //用于判断是否输入了数字,用于判断"i"前无数字的特殊情况
while (x>='0'&&x<='9'){ //读取数字
inpnum = true;
num *= 10;
num += x-'0';
x = getchar();
}
if (x=='.'){ //读取小数点后数字
x = getchar();
dec = 1;
while (x>='0'&&x<='9'){
dec /= 10;
num += dec*(x-'0');
x = getchar();
}
}
if (x=='i'){ //通过结尾是不是"i"来判断读取的是实数还是虚数
if (!inpnum) cplx.imag(cplx.imag()+(sgn?-1:1));//若"i"前无数字,系数为1
else cplx.imag(cplx.imag()+(sgn?-num:num));
x = getchar();
}else cplx.real(cplx.real()+(sgn?-num:num));
}
}
void outputComplex(complex<double> cplx){
if (cplx.imag() == 0) cout<<cplx.real(); //使用输出流,输出最简小数
else{
if (cplx.real() == 0){
if (cplx.imag() == 1) cout<<'i';
else if (cplx.imag() == -1) cout<<"-i";
else cout<<cplx.imag()<<'i';
}else{
if (cplx.imag() == 1) cout<<cplx.real()<<"+i";
else if (cplx.imag() == -1) cout<<cplx.real()<<"-i";
else cout<<cplx.real()<<showpos<<cplx.imag()<<noshowpos<<'i';//第二个复数保留前导'+'
}
}
}
int main(){
scanf("%d",&n);
while (n--){
inputComplex(c);
cout<<c<<" ";
outputComplex(c);
cout<<endl;
}
return 0;
}
测试:
主要是因为STL自带的complex类不支持按这种方式读入,又不想重新写一遍整个类,于是就写了这两个读入与输出函数。
有BUG欢迎反馈