编程:键盘输入10个数(可能为整形、浮点型、双精度型及其字符类型),分别利用函数重载和函数模板,求出其中的最大值和最小值。
时间: 2023-05-29 22:03:10 浏览: 87
C++函数重载的深入解析
函数重载:
```c++
#include <iostream>
#include <string>
using namespace std;
int max(int a[], int n)
{
int res = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] > res)
res = a[i];
}
return res;
}
double max(double a[], int n)
{
double res = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] > res)
res = a[i];
}
return res;
}
char max(char a[], int n)
{
char res = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] > res)
res = a[i];
}
return res;
}
template <typename T>
T min(T a[], int n)
{
T res = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] < res)
res = a[i];
}
return res;
}
int main()
{
int a[10];
double b[10];
char c[10];
for (int i = 0; i < 10; i++)
{
cin >> a[i];
b[i] = a[i];
c[i] = a[i];
}
cout << "max int: " << max(a, 10) << endl;
cout << "max double: " << max(b, 10) << endl;
cout << "max char: " << max(c, 10) << endl;
cout << "min int: " << min(a, 10) << endl;
cout << "min double: " << min(b, 10) << endl;
cout << "min char: " << min(c, 10) << endl;
return 0;
}
```
函数模板:
```c++
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T max(T a[], int n)
{
T res = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] > res)
res = a[i];
}
return res;
}
template <typename T>
T min(T a[], int n)
{
T res = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] < res)
res = a[i];
}
return res;
}
int main()
{
int a[10];
double b[10];
char c[10];
for (int i = 0; i < 10; i++)
{
cin >> a[i];
b[i] = a[i];
c[i] = a[i];
}
cout << "max int: " << max(a, 10) << endl;
cout << "max double: " << max(b, 10) << endl;
cout << "max char: " << max(c, 10) << endl;
cout << "min int: " << min(a, 10) << endl;
cout << "min double: " << min(b, 10) << endl;
cout << "min char: " << min(c, 10) << endl;
return 0;
}
```
阅读全文