实验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();
}