内存:128  时间:1

题目描述

定义一个复数类Complex,有两个数据成员real和imag分别表示复数的实部和虚部,都为double类型,
重载运算符“+”,使之能用于复数的加法运算。
参加运算的两个操作数可以都是复数类对象,也可以其中有一个是double另一个是复数类对象,
顺序任意。例如:c1 + c2,i + c1,c1 + i均合法(设i为double类型,c1,c2为复数)。

下面的程序中,在begin到end部分存在几处语法错误。请改正错误,使程序按下面输入输出的规定运行。
注意:只提交修改过的begin到end部分的代码。

#include <stdio.h>
#include <iostream.h>

//对begin到end之间部分的代码进行修改,只提交begin到end部分的代码
//******************** begin ********************

class Complex
{
  public:
   
      Complex(double r,double i); //构造函数
      void display(); //复数的输出
      Complex operator +(Complex c1,Complex c2);
      Complex operator +(double i);

  private:
      double real;
      double imag;
};

Complex operator +(Complex c1,Complex c2)
{
    Complex c;
    c.real = c1.real + c2.real;
    c.imag = c1.imag + c2.imag;
    return c;
}

Complex::Complex(double r,double i)
{
  real=r;
  imag=i;
}

void Complex::display()
{
    cout << "(" << real << "," << imag << "i)" <<endl;

Complex   Complex::operator +(double i)
{
    Complex c;
    c.real = real + i;
    c.imag = imag ;
    return c;

}

//********************* end ********************

   int main()
{
   double r1,  i1,  r2,  i2 ;
   cin>>r1>>i1; 
   cin>>r2>>i2; 

   Complex c1(r1,i1);
   Complex c2(r2,i2);
  
    Complex c3;
    c3=c1+c2;
    c3.display();

    c3= c1 + 3.3;
    c3.display();

    c3=3.3+c1;
    c3.display();

    return 0;
}

输入

第一个复数的实部和虚部

第二个复数的实部和虚部

输出

两个复数相加运算结果,复数和整数相加运算结果,整数和复数相加运算结果

样例输入

3 4
5 -10

样例输出

(8,-6i)
(6.3,4i)
(6.3,4i)

提示

有多种修改方式,只要保证修改完能运行出正确结果即可。

代码如下


#include <cstdio>
#include <iostream>
using namespace std;


class Complex
{
  public:
    Complex(){real=0;imag=0;}
      Complex(double r,double i); //构造函数
      void display(){cout << "(" << real << "," << imag << "i)" <<endl;} //复数的输出
     friend Complex operator +(Complex c1,Complex c2);
      Complex operator +(double i);
      friend Complex operator+(double,Complex);

  private:
      double real;
      double imag;
};
Complex operator+(double r,Complex a)
{
    return Complex(r+a.real,a.imag);
}
Complex operator +(Complex c1,Complex c2)
{
    Complex c;
    c.real = c1.real + c2.real;
    c.imag = c1.imag + c2.imag;
    return c;
}


Complex::Complex(double r,double i)
{
  real=r;
  imag=i;
}


Complex  Complex::operator +(double i)
{
    Complex c;
    c.real = real + i;
    c.imag = imag ;
    return c;

}

int main()
{
   double r1,  i1,  r2,  i2 ;
   cin>>r1>>i1;  
   cin>>r2>>i2;  

   Complex c1(r1,i1);
   Complex c2(r2,i2);
   
    Complex c3;
    c3=c1+c2;
    c3.display();

    c3= c1 + 3.3;
    c3.display();

    c3=3.3+c1;
    c3.display();

    return 0;
}

代码来源于互联网,仅供参考!