问题及代码:
/*
*Copyright (c)2015,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:number.cpp
*作 者:单昕昕
*完成日期:2015年4月11日
*版 本 号:v1.0
*问题描述:阅读教材例10.1。该例实现了一个复数类,但是美中不足的是,复数类的实部和虚部都固定只能是double型的。可以通过模板类的技术手段,设计Complex,使实部和虚部的类型为定义对象时指定的实际类型。
(1)要求类成员函数在类外定义。
(2)在此基础上,再实现减法、乘法和除法
*程序输入:无。
*程序输出:复数计算结果。
*/
/*
对于两个复数(a+bi)和(c+di)的运算结果
执行加法运算:(a+c),(b+d)i
执行减法运算:(a-c),(b-d)i
执行乘法运算:(a*c-b*d),(c*b+a*d)i
执行除法运算:(a*c+b*d)/(c*c+d*d),(a*d+b*c)/(c*c+d*d)
*/
#include <iostream>
#include <cmath>
using namespace std;
template <class numtype>
class Complex
{
private:
numtype real;
numtype imag;
public:
Complex()
{
real=imag=0;
}
Complex(numtype a,numtype b)
{
real=a;
imag=b;
}
void display();
Complex complex_add(Complex &cc); //执行加法运算
Complex complex_minus(Complex &cc); //执行减法运算
Complex complex_muliply(Complex &cc); //执行乘法运算
Complex complex_divided(Complex &cc); //执行除法运算
};
template <class numtype>
void Complex<numtype>::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex<numtype> &cc) //执行加法运算
{
Complex<numtype> c;
c.real=real+cc.real;
c.imag=imag+cc.imag;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_minus(Complex<numtype> &cc)//执行减法运算
{
Complex<numtype> c;
c.real=real-cc.real;
c.imag=imag-cc.imag;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_muliply(Complex<numtype> &cc)//执行乘法运算
{
Complex<numtype> c;
c.real=real*cc.real-imag*cc.imag;
c.imag=real*cc.imag+imag*cc.real;
return c;
}
template <class numtype>
Complex<numtype> Complex<numtype>::complex_divided(Complex<numtype> &cc)//执行除法运算
{
Complex<numtype> c;
c.real=(real*cc.real+imag*cc.imag)/(cc.real*cc.real+cc.imag*cc.imag);
c.imag=(real*cc.imag+imag*cc.real)/(cc.real*cc.real+cc.imag*cc.imag);
return c;
}
int main( )
{
//下面测试加法
Complex<int> c1(3,4),c2(5,-10),c3; //实部和虚部是int型
cout<<"c1=";
c1.display( );
cout<<"c2=";
c2.display( );
c3=c1.complex_add(c2);
cout<<"c1+c2=";
c3.display( );
Complex<double> c4(3.1,4.4),c5(5.34,-10.21),c6; //实部和虚部是double型
cout<<"c4=";
c4.display( );
cout<<"c5=";
c5.display( );
c6=c4.complex_add(c5);
cout<<"c4+c5=";
c6.display( );
//下面测试减法
c3=c1.complex_minus(c2);
cout<<"c1-c2=";
c3.display( );
c6=c4.complex_minus(c5);
cout<<"c4-c5=";
c6.display( );
//下面测试乘法
c3=c1.complex_muliply(c2);
cout<<"c1*c2=";
c3.display( );
c6=c4.complex_muliply(c5);
cout<<"c4*c5=";
c6.display( );
//下面测试除法
c3=c1.complex_divided(c2);
cout<<"c1/c2=";
c3.display( );
c6=c4.complex_divided(c5);
cout<<"c4/c5=";
c6.display( );
return 0;
}
运行结果:
知识点总结:
复数模板类。
复数的运算。
学习心得:
额。。复数的运算这个高中知识又被拿回来复习了一遍。。
注意每个函数前面都要加上模板使用声明!!