题目要求如下:
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
代码如下:
/*
* Copyright (c) 2013, 烟台大学计算机学院
* All rights reserved.
* 作 者: 沈远宏
* 完成日期:2014 年 06月17日
* 版 本 号:v1.0
* 问题描述:Description
定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算与输出操作。
(1)参加运算的两个运算量可以都是类对象,也可以其中有一个是实数,顺序任意。例如,c1+c2,d+c1,c1+d均合法(设d为实数,c1,c2为复数)。
(2)输出的算数,在复数两端加上括号,实部和虚部均保留两位小数,如(8.23+2.00i)、(7.45-3.40i)、(-3.25+4.13i)等。
编写程序,分别求两个复数之和、整数和复数之和,并且输出。
请在下面的程序段基础上完成设计:
Input
一个复数的实部和虚部,另一个复数的实部和虚部
一个复数的实部和虚部,一个实数
一个实数,一个复数的实部和虚部
Output
两个复数之和、复数和实数之和,实数和复数之和。
*/#include <iostream>
#include <iomanip>
using namespace std;
class Complex
{
public:
Complex():real(0),imag(0) {}
Complex(double r,double i):real(r),imag(i) {}
Complex operator+(Complex &);
Complex operator+(double &);
friend Complex operator+(double&,Complex &);
friend ostream& operator << (ostream& output, const Complex& c);
private:
double real;
double imag;
};
//将程序需要的其他成份写在下面,只提交begin到end部分的代码
//******************** begin ********************
Complex Complex::operator+(Complex &c2)
{
/*Cimplex c3;
c3.real=real+c2.real;
c3.imag=imag+c2.imag;*/
return Complex(real+c2.real,imag+c2.imag);
}
Complex Complex::operator+(double &d)
{
Complex c3;
c3.real=real+d;
c3.imag=imag;
return c3;
}
Complex operator+(double&d,Complex &c)
{
Complex c3;
c3.real=d+c.real;
c3.imag=c.imag;
return c3;
}
ostream& operator << (ostream& output, const Complex& c)
{
cout<<fixed<<setprecision(2);
if(c.imag>0)
{
cout<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;
}
else
{
cout<<"("<<fixed<<setprecision(2)<<c.real<<"-"<<fixed<<setprecision(2)<<(-c.imag)<<"i)"<<endl;
}
}
//********************* end ********************
int main()
{
//测试复数加复数
double real,imag;
cin>>real>>imag;
Complex c1(real,imag);
cin>>real>>imag;
Complex c2(real,imag);
Complex c3=c1+c2;
cout<<"c1+c2=";
cout<<c3;
//测试复数加实数
double d;
cin>>real>>imag;
cin>>d;
c3=Complex(real,imag)+d;
cout<<"c1+d=";
cout<<c3;
//测试实数加复数
cin>>d;
cin>>real>>imag;
c1=Complex(real,imag);
c3=d+c1;
cout<<"d+c1=";
cout<<c3;
return 0;
}
运行结果:
OJ要求结果输出例样: