复数相加减(练手)[第二版]

作者在 2006-09-05 06:05:00 发布以下内容
#include <iostream.h>
class ComplexNumber
{
 int real;
 int imaginary;
 int num;
public:
 ComplexNumber(){real=0;imaginary=0;}
 ComplexNumber(int a,int b){real=a;imaginary=b;}
 void SetReal(int real);
 void SetImaginary(int imaginary);
 void SetNum(int num);
 ComplexNumber operator+(ComplexNumber &second);
 ComplexNumber operator-(ComplexNumber &second);
 void disp();
 ~ComplexNumber();
};
void ComplexNumber::SetReal(int real)
{
 this->real=real;
}
void ComplexNumber::SetImaginary(int imaginary)
{
 this->imaginary=imaginary;
}
void ComplexNumber::SetNum(int num)
{
 this->num=num;
}
void ComplexNumber::disp()

 if(real!=0)
 {
  if(imaginary>0)
  {
   cout<<real<<'+'<<imaginary<<"i\n";
  }
  else if(imaginary<0)
  {
   cout<<real<<imaginary<<"i\n";
  }
  else
  {
   cout<<real<<"\n";
  }
 }
 if(real==0)
 {
  if(imaginary!=0)
  {
   cout<<imaginary<<"i\n";
  }
  else
  {
   cout<<real<<"\n";
  }
 }
}
ComplexNumber ComplexNumber::operator+(ComplexNumber &second)
{
 return ComplexNumber(real+second.real,imaginary+second.imaginary);
}
ComplexNumber ComplexNumber::operator-(ComplexNumber &second)
{
 return ComplexNumber(real-second.real,imaginary-second.imaginary);
}
ComplexNumber::~ComplexNumber()
{
}
void main()
{
 ComplexNumber firstNumber;
 firstNumber.SetNum(1);
 ComplexNumber secondNumber;
 secondNumber.SetNum(2);
 ComplexNumber sum;
 sum.SetNum(3);
 int set;
 cout<<"Please input the real part of the first number:";
 cin>>set;
 firstNumber.SetReal(set);
 cout<<"Please input the imaginary part of the first number:";
 cin>>set;
 firstNumber.SetImaginary(set);
 cout<<"Please input the real part of the second number:";
 cin>>set;
 secondNumber.SetReal(set);
 cout<<"Please input the imaginary part of the first number:";
 cin>>set;
 secondNumber.SetImaginary(set);
 sum=firstNumber+secondNumber;
 sum.disp();
 sum=firstNumber-secondNumber;
 sum.disp();
}
c++开拓 | 阅读 926 次
文章评论,共0条
游客请输入验证码