实验六 函数模板和类模板

1.编写一个求任意类型数组中最大元素和最小元素的程序,要求将求最大元素和最小元素的函数设计成函数模板

#include<iostream>
using namespace std;
template<typename T>
T MAX(T number[], int n)
{
	T arr = number[0];
	for (int i = 0; i < n; i++)
	{
		if (arr < number[i])
		{
			arr = number[i];
		}
	}
	return arr;
}
template<typename D>
D MIN(D number[], int n)
{
	D brr = number[0];
	for (int i = 0; i < n; i++)
	{
		if (brr > number[i])
		{
			brr = number[i];
		}
	}
	return brr;
}
int main()
{
	int n;
	cin >> n;

	int* intm = new int [n];
	for (int i = 0; i < n; i++)
	{
		cin >> intm[i];
	}
	int int_max = MAX(intm, n);
	cout << "int_max:" << int_max << endl;
	int int_min = MIN(intm, n);
	cout << "int_min:" << int_min << endl;

	double* doublem = new double[n];
	for (int i = 0; i < n; i++)
	{
		cin >> doublem[i];
	}
	double dmax = MAX(doublem, n);
	cout << "dmax:" << dmax << endl;
	double dmin = MIN(doublem, n);
	cout << "dmin:" << dmin << endl;
	delete[] intm;
	delete[] doublem;
	return 0;
}

2.编写一个程序,求输入数的平方根。设置异常处理,对输入负数的情况给出提示。

提示:#include<math>

#include <iostream>

using namespace std;

double Sq(double x)

{

    if (x < 0)

       throw x;

    return sqrt(x);

}

……

#include<iostream>
#include<cmath>
using namespace std;
double Sq(double x)
{
	if (x < 0)
		throw x;
	return sqrt(x);
}
int main()
{
	double x, y;
	cin >> x;
	cin >> y;
	double sq, sq1;
	try
	{
		sq = Sq(x);
		cout << "sqrt(x):" << sq << endl;
		sq1 = Sq(y);
		cout << "sqrt(y):" << sq1 << endl;
	}
	catch(double)
	{
		cout << "错误" << endl;
		
	}
	
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值