Online Judge——1011. 复数类(c++)

本文介绍了一个复数类的设计与实现,该类通过C++运算符重载实现了复数的基本运算,如加减乘除及复合赋值等操作,并提供了一种友元函数的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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

#include <iostream>
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 <<endl;
  cout << z1 - z2 <<endl;
  cout << z1 * z2 <<endl;
  cout << z1 / z2 <<endl;
  cout << (z1 += z2) <<endl;
  cout << (z1 -= z2) <<endl;
  cout << (z1 *= z2) <<endl;
  cout << (z1 /= z2) <<endl;

  return 0;
}

输入格式

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

第二行是两个整数c, d(0<|c|+1,|d|<100010<|c|+1,|d|<10001),表示复数c+dic+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 <iostream>
#include <iomanip>

using namespace std;

class MyComplex{
private:
  double x, y;

public:
  MyComplex() {
    x = 0;
    y = 0;
  }
  MyComplex(double xx, double yy) {
    x = xx;
    y = yy;
  }
  friend ostream& operator << (ostream& output, MyComplex c) {
    output << setiosflags(ios::fixed) << setprecision(2) << c.x << " " << c.y; // 保留两位
    return output;
  }
  friend istream& operator >> (istream& input, MyComplex& c) {
    input >> c.x >> c.y;
    return input;
  }
  MyComplex operator + (const MyComplex& c) {
    return MyComplex(x + c.x, y + c.y);
  }
  MyComplex operator - (const MyComplex& c) {
    return MyComplex(x - c.x, y - c.y);
  }
  MyComplex operator * (const MyComplex& c) {
    return MyComplex(x * c.x - y * c.y, x * c.y + y * c.x);
  }
  MyComplex operator / (const MyComplex& c) {
    return MyComplex((x * c.x + y * c.y) / (c.x * c.x + c.y * c.y), ( - x * c.y + y * c.x) / (c.x * c.x + c.y * c.y));
  }
  MyComplex& operator += (const MyComplex& c) {
    *this = *this + c;
    return *this;
  }
  MyComplex& operator -= (const MyComplex& c) {
    *this = *this - c;
    return *this;
  }
  MyComplex& operator *= (const MyComplex& c) {
    *this = *this * c;
    return *this;
  }
  MyComplex& operator /= (const MyComplex& c) {
    *this = *this / c;
    return *this;
  }

};
int main(int argc, char const *argv[]) {
  MyComplex z1;
  MyComplex z2;

  cin >> z1 >> z2;

  cout << z1 + z2 <<endl;
  cout << z1 - z2 <<endl;
  cout << z1 * z2 <<endl;
  cout << z1 / z2 <<endl;
  cout << (z1 += z2) <<endl;
  cout << (z1 -= z2) <<endl;
  cout << (z1 *= z2) <<endl;
  cout << (z1 /= z2) <<endl;

  return 0;
}

收获:

复习c++友元、运算符重载。 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值