[面向对象课]复数的输入输出
大概是前几天面向对象期中考的时候有这么一个题…需要读入和输出复数(还都是浮点数),当时写了好久才过,虽然确实不算难,但当时也卡了好久…
#include<bits/stdc++.h>
using namespace std;
double read(string str){
// cout<<"str="<<str<<endl;
double ans=0;
int len=str.length(),pos=-1,f=1;
if(str[len-1]=='i'){
if(len-2>=0){
if(str[len-2]=='-')return -1;
if(str[len-2]=='+')return 1;
}else return 1;
len--;
}
for(int i=0;i<len;i++){
if(str[i]=='+')continue;
if(str[i]=='-'){
f=-1;
continue;
}
if(str[i]!='.')ans=ans*10+str[i]-'0';
else pos=i;
}
if(pos!=-1){
pos=len-1-pos;
while(pos){
pos--;
ans/=10;
}
}
return ans*f;
}
int main(){
// freopen("input.txt","r",stdin);
string str;cin>>str;
cout<<"complex"<<' '<<str<<endl;
int len=str.length();
double x,y;
if(str[len-1]!='i')x=read(str),y=0;
else{
int p=len-1;
while(p&&str[p]!='+'&&str[p]!='-')p--;
y=read(str.substr(p,len-p));
p--;
if(p<0)x=0;
else x=read(str.substr(0,p+1));
}
cout<<"the real part is "<<x<<endl;
cout<<"and the imaginary part is "<<y;
return 0;
}
以及还有一个封装过的复数的输入输出:
#include<bits/stdc++.h>
using namespace std;
int read(string str);
class Complex{
private:
int real,image;
public:
Complex(int _r=0,int _i=0):real(_r),image(_i){}
Complex operator *(const Complex &rhs){
return Complex(real*rhs.real-image*rhs.image,
real*rhs.image+image*rhs.real);
}
friend istream& operator >>(istream &in,Complex &t){
string str;in>>str;
int len=str.length();
if(str[len-1]!='i')t.real=read(str),t.image=0;
else{
int p=len-1;
while(p&&str[p]!='+'&&str[p]!='-')p--;
t.image=read(str.substr(p,len-p));
p--;
if(p<0)t.real=0;
else t.real=read(str.substr(0,p+1));
}
return in;
}
friend ostream& operator<<(ostream &out,const Complex &t){
if(!t.real&&!t.image){out<<0;return out;}
if(t.real)out<<t.real;
if(t.image){
if(t.real||t.image<0){
if(t.image<0)out<<'-';
else out<<'+';
}
if(abs(t.image)!=1)out<<abs(t.image);
out<<'i';
}
return out;
}
};
int read(string str){
int ans=0,len=str.length(),f=1;
if(str[len-1]=='i'){
if(len-2>=0){
if(str[len-2]=='-')return -1;
if(str[len-2]=='+')return 1;
}else return 1;
len--;
}
for(int i=0;i<len;i++){
if(str[i]=='+')continue;
if(str[i]=='-'){f=-1;continue;}
ans=ans*10+str[i]-'0';
}
return ans*f;
}
int main(){
Complex a,b;
cin>>a>>b;
cout<<a*b;
return 0;
}