C++面向对象程序设计实训4

第1关:实践题

求最大值

#include <iostream>        						// 编译预处理命令
#include <string.h>        						// 编译预处理命令
using namespace std;							// 使用命名空间std 

template <class ElemType>
ElemType Max(ElemType x, ElemType y)
{
    /********* Begin *********/
    // 求x, y的最大值
	return x>y?x:y;



    /********* End *********/
}

char *Max(char *s1, char *s2)
{
    /********* Begin *********/
    // 求s1,s2的最大值
return strcmp(s1,s2)>0?s1:s2;



    /********* End *********/
}

template <class ElemType>
ElemType Max(ElemType x, ElemType y, ElemType z) 
{
    /********* Begin *********/
    // 求x,y,z的最大值
ElemType tem=x>y?x:y;
return tem>z?tem:z;




    /********* End *********/
}

template <class ElemType>
ElemType Max(ElemType a[], int n)
{
    /********* Begin *********/
    // 求a[0],a[1],...,a[n-1]的最大值
ElemType m=a[0];
for(int i=1;i<n;i++)
if(m<a[i]) m=a[i];
return m;



    /********* End *********/
}

第2关:实践题

建立复数类模板

#include <iostream>        						// 编译预处理命令
using namespace std;							// 使用命名空间std 

// 声明复数类模板
template <class ElemType>
class Complex
{
private:
// 数据成员
	// 在下面对real和image进行声明
	/********* Begin *********/
	ElemType real;
    ElemType image;


	
	/********* End *********/

public:
// 公有函数	
	Complex(ElemType r = 0, ElemType i = 0): real(r), image(i){ }
	// 在下面对Show、Add和Sub函数进行声明
	/********* Begin *********/
void Show() const;
static Complex Add(const Complex &z1,const Complex &z2);
static Complex Sub(const Complex &z1,const Complex &z2);




	/********* End *********/
};

// 在下面定义成员函数

// 显示复数
template <class ElemType>
void Complex<ElemType>::Show() const			
{
	// 显示复数据,显示格式说“实部+虚部i”,例如:2+3i, 2-3i, -2+3i, 8, -8, 8i, -5i, 0
	// 在显示完复数后不用加换行符
	/********* Begin *********/

	if (real != 0)
	{	// real非0,对image进行讨论(为负,为0,为正),可能输出示例:2-3i, 8, -8, 2+3i
if(image<0) cout<<real<<image<<"i";
else if(image==0) cout<<real;
else cout<<real<<"+"<<image<<"i";





	}
	else
	{	// real为0,对image进行讨论(为0,非0),可能输出示例:0, 8i, -5i 
if(image==0) cout<<real;
else cout<<image<<"i";





	}
	
	/********* End *********/
}

// 复数加法
template <class ElemType>
Complex<ElemType> Complex<ElemType>::Add(const Complex &z1,	const Complex &z2)
{ 
	// 返回复数z1与z2之和
	/********* Begin *********/
Complex z(z1.real+z2.real,z1.image+z2.image);
return z;






	/********* End *********/
}

// 复数减法
template <class ElemType>
Complex<ElemType> Complex<ElemType>::Sub(const Complex &z1,	const Complex &z2)	
{ 
	// 返回复数z1与z2之差
	/********* Begin *********/
Complex z(z1.real-z2.real,z1.image-z2.image);
return z;






	/********* End *********/
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值