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;
}