上交OJ-1011. 复数类

1011. 复数类


题目描述

写一个复数类,实现以下程序主函数中所需要的功能。

#include 
using namespace std;

class MyComplex
{
private:
  double x,y;
public:
  /* Implementation of MyComplex */
};

int main()
{
  MyComplex z1;
  MyComplex z2;

  cin >> z1 >> z2;

  cout << z1 + z2 <

输入格式

输入包括两行,第一行是两个整数a, b(0<|a|+1,|b|<10001),表示复数a+bi。

第二行是两个整数c, d(0<|c|+1,|d|<10001),表示复数c+di。输入数据保证不出现除以0的情况。

输出格式

输出包括八行,对应所给程序中的输出。注意输出浮点数保留2位小数。

Sample Input 1

3 6
-3 5

Sample Output 1

0.00 11.00
6.00 1.00
-39.00 -3.00
0.62 -0.97
0.00 11.00
3.00 6.00
-39.00 -3.00
3.00 6.00

Sample Input 2

5 9
5 -9

Sample Output 2

10.00 0.00
0.00 18.00
106.00 0.00
-0.53 0.85
10.00 0.00
5.00 9.00
106.00 0.00
5.00 9.00

分析

这是对运算符和输入输出重载的题目。

#include 
#include 
using namespace std;

class MyComplex
{
private:
  double x,y;
public:
  /* Implementation of MyComplex */
  MyComplex(){x=0; y=0;}
  MyComplex(double r,double i){x=r; y=i;}
  
  friend ostream& operator << (ostream&, MyComplex);
  friend istream& operator >> (istream&, MyComplex&);
  
  MyComplex operator + (const MyComplex &c2);
  MyComplex operator - (const MyComplex &c2);
  MyComplex operator * (const MyComplex &c2);
  MyComplex operator / (const MyComplex &c2);
  MyComplex& operator += (const MyComplex &c2);
  MyComplex& operator -= (const MyComplex &c2);
  MyComplex& operator *= (const MyComplex &c2);
  MyComplex& operator /= (const MyComplex &c2);
};

ostream& operator << (ostream& output, MyComplex c) //定义运算符“<<”重载函数
{
  output<> (istream& input, MyComplex& c) //定义运算符“<<”重载函数
{
  input>>c.x>>c.y;
  return input;
}

MyComplex MyComplex::operator + (const MyComplex &c2)//定义运算符“+”重载函数
{
  return MyComplex(x+c2.x, y+c2.y);
}

MyComplex MyComplex::operator - (const MyComplex &c2)//定义运算符“+”重载函数
{
  return MyComplex(x-c2.x, y-c2.y);
}

MyComplex MyComplex::operator * (const MyComplex &c2)//定义运算符“+”重载函数
{
  return MyComplex(x*c2.x-y*c2.y, x*c2.y+y*c2.x);
}

MyComplex MyComplex::operator / (const MyComplex &c2)//定义运算符“+”重载函数
{
  return MyComplex((x*c2.x+y*c2.y)/(c2.x*c2.x+c2.y*c2.y), (-x*c2.y+y*c2.x)/(c2.x*c2.x+c2.y*c2.y));
}

MyComplex& MyComplex::operator += (const MyComplex &c2)//定义运算符“+”重载函数
{
  *this = *this + c2;
  return *this;
}

MyComplex& MyComplex::operator -= (const MyComplex &c2)//定义运算符“+”重载函数
{
  *this = *this - c2;
  return *this;
}

MyComplex& MyComplex::operator *= (const MyComplex &c2)//定义运算符“+”重载函数
{
  *this = *this * c2;
  return *this;
}

MyComplex& MyComplex::operator /= (const MyComplex &c2)//定义运算符“+”重载函数
{
  *this = *this / c2;
  return *this;
}

int main()
{
  MyComplex z1;
  MyComplex z2;

  cin >> z1 >> z2;

  cout << z1 + z2 <

你可能感兴趣的:(上交OJ-1011. 复数类)