C++的问题,提交了是Time Limit Exceeded,求解?

https://img4.mukewang.com/5b8e3fe10001b69e09110555.jpg


#include<iostream>

#include<string>

using namespace std;

class complex

{

public:

complex(){}

complex(double m,double n)

{

this->m=m;

this->n=n;

}

complex &operator+(complex &s)

{

complex c;

c.m=m+s.m;

c.n=n+s.n;

return c;

}

complex &operator-(complex &s)

{

complex c;

c.m=m-s.m;

c.n=n-s.n;

return c;

}

complex &operator*(complex &s)

{

complex c;

c.m=(m*s.m)-(n*s.n);

c.n=(n*s.m)+(m*s.n);

return c;

}

complex &operator/(complex &s)

{

complex c;

c.m=((m*s.m)+(n*s.n))/(s.m*s.m+s.n*s.n);

c.n=((n*s.m)-(m*s.n))/(s.m*s.m+s.n*s.n);

return c;

}

void show()

{

if(m==0&&n!=0)

cout<<n<<"i"<<endl;

else if(n<0)

cout<<m<<"-"<<n<<"i"<<endl;

else if(n==0&&m!=0)

cout<<m<<endl;

else

cout<<m<<"+"<<n<<"i"<<endl;

}

private:

double m,n;

};

int main()

{

int t;

double m,n,m1,n1;

char c;

cin>>t;

for(int i=0;i<t;i++)

{

cin>>m>>n;

complex a(m,n);

cin>>c;

while(c!='=')

{

if(c=='+')

{

cin>>m>>n;

complex b(m,n);

a=a+b;

}

else if(c=='-')

{

cin>>m>>n;

complex b(m,n);

a=a-b;

}

else if(c=='*')

{

cin>>m>>n;

complex b(m,n);

a=a*b;

}

else if(c=='/')

{

cin>>m1>>n1;

complex b(m1,n1);

a=a/b;

}

cin>>c;

}

if(c=='=')

{

if(m1!=0&&n1!=0)

{

a.show();

continue;

}

else

{

cout<<"divide by zero"<<endl;

}

}

}

}


慕盖茨8171496
浏览 2487回答 3
3回答

慕盖茨8171496

。。。

慕盖茨8171496

运行结果

AAnonymous

回答好像被吞了,再说下你重载运算符时,返回引用。但是你返回的是你创建的临时对象。运算符调用完成后它会被销毁。注意,这几个运算符重载,调用时实际上是对运算符左边的对象调用他重载的成员运算符,参数是运算符右边的对象。所以你可以这么做。1,不必返回引用,直接值返回,返回的是对象的拷贝2,仍然使用左值引用,返回 *this3,使用右值引用,返回 std::move(c)
打开App,查看更多内容
随时随地看视频慕课网APP