c++基础实验

实验4_1:函数模板实验:用函数模板方法编写程序,对给各种不同类型的三个数分别求最大数。

#include<iostream>
using namespace std;
//实验4_1:函数模板实验:用函数模板方法编写程序,对给各种不同类型的三个数分别求最大数。
template<class t>
t max(t a, t b, t c)
{
	t max;
	max = (a > b ? a : b) > c ? (a > b ? a : b) : c;
	return max;
}

int main()
{
	int a, b, c;
	cout << "请输入整数" << endl;

	cin >> a >> b >> c;
	cout << max(a, b, c) << endl;
	
	cout << "请输入浮点数" << endl;
	double d, e, f;
	cin >> d >> e >> f;
	cout << max(d, e, f)<<endl;

	cout << "请输入字符串" << endl;

	char g, h, i;
	cin >> g >> h >> i;
	cout << max(g, h, i) << endl;


}

实验4_2: 编程序创建一个类模板,可以对不同的数据类型的数组分别进行初始化、添加数据、求和、求平均值、显示数组等功能。

要求:编程序上机通过,写出运行结果。

#include<iostream>
using namespace std;
template<class t>
class myarray
{//指针指向堆区开辟的数组
	t* p;
	//数组容量
	int capcity;
	//数组大小
	int size;

public:
	//初始化接口
	myarray(int c)
	{
		this->capcity = c;
		this->size = 0;
		this->p = new t[capcity];
	}
	//添加元素
	void add(t val)
	{
		if (capcity = size)
		{
			return;
		}
		cout << "请输入" << val << "个数" << endl;
		for (int i = 0; i < val; i++)
		{
			cin >> p[i];
			this->size++;
		}
	}
	void sum()
	{
		t s = p[0];
		for (int i = 1; i < size; i++)
		{
			s += p[i];
		}
		cout << "该数组的和:"<<s << endl;
		
	}
	void average()
	{

		t s = p[0];
		for ( int i = 1; i < size; i++)
		{
			s += p[i];
		}
		s = s / size;

		cout << "该数组的平均值:" << s << endl;
	}
	void show()
	{
		cout << "显示数组:";
		for ( int i = 0; i < size; i++)
		{
			cout << p[i] << "  ";
		}
		cout << endl;
	}
	~myarray()
	{
		if (p != NULL)
		{
			delete[]p;
			p = NULL;
		}
	}
};
int main()
{
	myarray<int> i(100);
	cout << "请输入整数的个数:" << endl;
	int len;
	cin >> len;
	i.add(len);
	i.sum();
	i.average();
	i.show();

	myarray<double> d(100);
	cout << "请输入浮点数的个数:" << endl;
	cin >> len;
	d.add(len);
	d.sum();
	d.average();
	d.show();


	myarray<char> c(100);
	cout << "请输入字符的个数:" << endl;
	cin >> len;
	c.add(len);
	c.sum();
	c.average();
	c.show();

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

0x3f3f3f3f3f

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值